Spring的@ConfigurationProperties注解可用于綁定外部配置文件中的屬性到JavaBean中,從而實(shí)現(xiàn)動(dòng)態(tài)更新配置。
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();
}
需要注意的是,動(dòng)態(tài)更新配置可能會(huì)導(dǎo)致線程安全問(wèn)題,所以在并發(fā)環(huán)境下應(yīng)謹(jǐn)慎使用動(dòng)態(tài)更新配置功能。