如果我们想对一个bean的所有String类型的属性注入设置一个修正器,使其所有的注入内容均转换成大写,我们可以借助与Spring提供的 BeanPostProcessor接口
首先定义一个类,实现BeanPostProcessor接口,完成注入属性的大小写转换
public
class
UppercassModifier
implements
BeanPostProcessor
...
{
public Object postProcessBeforeInitialization(Object bean,String name) throws BeansException...{
//取得bean的field成员
Field[] fields=bean.getClass().getDeclaredFields();
for(int i=0;i<fields.lengtj;i++)...{
//针对string类型的field成员加以修正
if(fields[i].getType().equals(String.class))...{
fiels[i].setAccessible(true);
try...{
String orginal=(String)field[i].get(bean);
field[i].set(bean,orginal.toUpperCase());
}catch(Exception e)...{
}
}
}
return bean;
}
}
public Object postProcessBeforeInitialization(Object bean,String name) throws BeansException...{
//取得bean的field成员
Field[] fields=bean.getClass().getDeclaredFields();
for(int i=0;i<fields.lengtj;i++)...{
//针对string类型的field成员加以修正
if(fields[i].getType().equals(String.class))...{
fiels[i].setAccessible(true);
try...{
String orginal=(String)field[i].get(bean);
field[i].set(bean,orginal.toUpperCase());
}catch(Exception e)...{
}
}
}
return bean;
}
}
spring bean
public
class
HelloBean
...
{
private String helloworld;
setter/getter方法
}
private String helloworld;
setter/getter方法
}
配置文件
<
bean
id
="uppercaseModifier"
class
="demo.UppercaseModifier"
/>
< bean id ="helloBean" class ="demo.HelloBean" >
< property name ="helloworld" value ="Hello" />
</ bean >
< bean id ="helloBean" class ="demo.HelloBean" >
< property name ="helloworld" value ="Hello" />
</ bean >
测试后,注入的Hello会自动转换成HELO