在Bean被创建以及装配后,BeanPostProcessor 接口为你提供了二次机会来修改这个bean。
public interface BeanPostProcessor{
Object postProcessBeforeInitialization(Object bean, String name) throws BeansException;
Object postProcessAfterInitialization(Object bean, String name) throws BeansException;
}
public class Fuddifier implements BeanPostProcessor{
public Object postProcessAfterInitialization(Object bean, String name){
Field[] fileds = bean.getClass().getDeclaredFields();
try{
for(int i=0;i<fields.length;i++){
if(fileds[i].getType().equals(java.lang.String.class)){
fields[i].setAccessible(true);
String original = (String) fields[i].get(bean);
fields[i].set(bean, fuddify(original));
}
}
} catch(IllegalAccessException e){
e.printStackTrace();
}
return bean;
}
private String fuddify(String orig){
if(orig == null ) return orig;
return orig.replaceAll("(r|l)","w").replaceAll("(R|L)","W");
}
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException{
return bean;
}
}
spring 还可以监听事件和发布事件,只需要实现相应的接口。