如果我们想对一个bean的所有String类型的属性注入设置一个修正器,使其所有的注入内容均转换成大写,我们可以借助与Spring提供的BeanPostProcessor接口
首先定义一个类,实现BeanPostProcessor接口,完成注入属性的大小写转换
public
class
UppercassModifier
implements
BeanPostProcessor
...
{
publicObjectpostProcessBeforeInitialization(Objectbean,Stringname)throwsBeansException...{
//取得bean的field成员
Field[]fields=bean.getClass().getDeclaredFields();
for(inti=0;i<fields.lengtj;i++)...{
//针对string类型的field成员加以修正
if(fields[i].getType().equals(String.class))...{
fiels[i].setAccessible(true);
try...{
Stringorginal=(String)field[i].get(bean);
field[i].set(bean,orginal.toUpperCase());
}catch(Exceptione)...{
}
}
}
returnbean;
}
}
publicObjectpostProcessBeforeInitialization(Objectbean,Stringname)throwsBeansException...{
//取得bean的field成员
Field[]fields=bean.getClass().getDeclaredFields();
for(inti=0;i<fields.lengtj;i++)...{
//针对string类型的field成员加以修正
if(fields[i].getType().equals(String.class))...{
fiels[i].setAccessible(true);
try...{
Stringorginal=(String)field[i].get(bean);
field[i].set(bean,orginal.toUpperCase());
}catch(Exceptione)...{
}
}
}
returnbean;
}
}
spring bean
<
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
原文链接:https://www.f2er.com/javaschema/288181.html