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();
}
需要注意的是,动态更新配置可能会导致线程安全问题,所以在并发环境下应谨慎使用动态更新配置功能。