PropertyChangeSupport屬性變動監聽器
- RefreshScope刷新spring bean遇到問題(詳見代碼註釋) 文檔.
@RefreshScope
public class ConfigProperties implements InitializingBean{
//屬性變動監聽器
private PropertyChangeSupport listeners = new PropertyChangeSupport(this);
/**
* 必須在構造方法中觸發,執行完構造方法纔會觸發set方法,這樣就能夠監聽到屬性的變化。經過refreshScope刷新bean屬性。
* 不能afterPropertiesSet和@PostConstruct方法中觸發監聽,由於set方法會在註冊監聽以前觸發
*/
public ConfigProperties() {
System.out.println("ConfigProperties invoke");
this.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
System.out.println("ConfigProperties:"+evt.getNewValue()+"----"+evt.getOldValue()+"----"+evt.getSource()+"----"+evt.getPropertyName()+"----"+evt.getPropagationId());
}
});
}
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("afterPropertiesSet invoke");
}
@PostConstruct
public void init() {
System.out.println("@PostConstruct invoke");
}
@PreDestroy
public void destroy(){
this.removePropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
}
});
}
public void setTaxFactory(Map<String, String> taxFactory) {
listeners.firePropertyChange("taxFactory", this.taxFactory, taxFactory);
this.taxFactory = taxFactory;
}
/**
* 增長屬性變動監聽器
* @param listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
listeners.addPropertyChangeListener(listener);
}
/**
* 增長屬性變動監聽器
* @param listener
*/
public void addPropertyChangeListener(String name,PropertyChangeListener listener) {
listeners.addPropertyChangeListener(name,listener);
}
/**
* 移除屬性變動監聽器
* @param listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
listeners.removePropertyChangeListener(listener);
}
}