@ConfigurationProperties和@Component搭配使用後,可以讓配置類
遇到一個新問題注解@ConfigurationProperties應用在類上時不能實作動态重新整理,經過查閱相關資料後,總結了兩個方法。@ApolloConfigChangeListener主要用來自動注冊ConfigChangeListener
(1)通過RefreshScope實作重新整理
配置類加上RefreshScope注解
@Component
@ConfigurationProperties(prefix = "order")
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@RefreshScope
public class OrderProperties {
private Integer payTimeSeconds;
private Integer createFrequencySeconds;
private Integer timeOut;
@Override
public String toString() {
return "OrderProperties{" +
"payTimeSeconds=" + payTimeSeconds +
", createFrequencySeconds=" + createFrequencySeconds +
", timeOut=" + timeOut +
'}';
}
}
@RestController
public class ApolloController3 {
@Autowired
private OrderProperties orderProperties;
@Autowired
private RefreshScope refreshScope;
@RequestMapping("demo3")
public String testDemo3(){
return orderProperties.toString();
}
@ApolloConfigChangeListener(value = "application",interestedKeyPrefixes = "order.")//監聽的是namespace
public void refresh(ConfigChangeEvent configChangeEvent){
//refreshScope.refresh(name)這個name為加了@ConfigurationProperties注解的Bean name
refreshScope.refresh("orderProperties");
Set<String> keySet = configChangeEvent.changedKeys();
for (String key:keySet) {
System.out.println("key的值為:"+key+",對應的值為:"+configChangeEvent.getChange(key));
}
System.out.println(orderProperties.toString());
}
}
(2)通過Spring的事件驅動基于EnvironmentChangeEvent實作重新整理
OrderProperties配置類可以去掉@RefreshScope注解
@Component
public class OrderPropertyRefresh implements ApplicationContextAware {
@Autowired
private OrderProperties orderProperties;
@Autowired
private ApplicationContext applicationContext;
@ApolloConfigChangeListener(interestedKeyPrefixes = "order.")
public void refresh(ConfigChangeEvent changeEvent){
this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
System.out.println(orderProperties.toString());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}