import java.lang.reflect.Field;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
public class UpperCaseModifier implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String name)
throws BeansException {
// TODO Auto-generated method stub
System.out.println("对象" + name + "实例化完成");
return bean;
}
@Override
public Object postProcessBeforeInitialization(Object bean, String name)
throws BeansException {
System.out.println("对象" + name + "开始实例化");
// 取 bean 所有属性
Field[] fields = bean.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++) {
//判断 name 字段
if (fields[i].getName().equals("name")) {
//设置该字段可访问
fields[i].setAccessible(true);
try {
String original = (String) fields[i].get(bean);
System.out.println(original);
fields[i].set(bean, original.toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
}
}
return bean;
}
}
以上代码实现将 name 属性值中的小写字母转变为大写字母;
BeanPostProcessor 接口包括两个方法:
postProcessAfterInitialization:在实例化之后进行操作
postProcessBeforeInitialization:在实例化之前进行操作
要在配置文件中引入该类:
<bean id="upperCaseModifier" class="UpperCaseModifier"></bean>
渣渣就得在 Bug 中挣扎