Spring的@ConfigurationProperties注解可用于綁定外部配置文件中的屬性到JavaBean中,從而實現動態更新配置。
myapp.username=default
myapp.password=defaultPassword
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String username;
private String password;
// getter and setter methods
}
@SpringBootApplication
@EnableConfigurationProperties(MyAppProperties.class)
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@Autowired
private MyAppProperties myAppProperties;
public void someMethod() {
String username = myAppProperties.getUsername();
String password = myAppProperties.getPassword();
}
需要注意的是,動態更新配置可能會導致線程安全問題,所以在并發環境下應謹慎使用動態更新配置功能。