Spring中的PropertyEditor的简单实用方法

用于属性的转换,是BeanPostProcessor的一种,比如有如下两个java类: 
01package com.google.spring.applicationContext;
02 
03public class Computer
04{
05    private String name;
06     
07    public Computer()
08    {
09         
10    }
11     
12    public Computer(String name)
13    {
14        this.name = name;
15    }
16 
17    public String getName()
18    {
19        return name;
20    }
21 
22    public void setName(String name)
23    {
24        this.name = name;
25    }
26     
27}

01package com.google.spring.applicationContext;
02 
03public class Person
04{
05    private Computer computer ;
06 
07    public Computer getComputer()
08    {
09        return computer;
10    }
11 
12    public void setComputer(Computer computer)
13    {
14        this.computer = computer;
15    }
16     
17     
18}

假若在XML中进行如下配置: 
1<bean id="person" class="com.google.spring.applicationContext.Person">
2   <property name="computer">
3       <value>lenovo</value>
4   </property>
5</bean>

这时候在getBean("person")的时候是有问题的。通过PropertyEditor 可以将字符串映射为其它类型: 
01package com.google.spring.applicationContext;
02 
03import java.beans.PropertyEditorSupport;
04 
05public class ComputerTypeEditor extends PropertyEditorSupport
06{
07    private String format;
08 
09    public String getFormat()
10    {
11        return format;
12    }
13 
14    public void setFormat(String format)
15    {
16        this.format = format;
17    }
18     
19    public void setAsText(String text)
20    {
21        Computer computer = new Computer(text);
22        this.setValue(computer);
23    }
24}

在XML中注册一下该转换器: 
01<bean id="customEditorConfigure"class="org.springframework.beans.factory.config.CustomEditorConfigurer">
02     <property name="customEditors">
03         <map>
04            <entry key="com.google.spring.applicationContext.Computer">
05               <beanclass="com.google.spring.applicationContext.ComputerTypeEditor">
06                   <property name="format">
07                       <value>upperCase</value>
08                   </property>
09               </bean>
10            </entry>
11         </map>
12     </property>
13</bean>

这时候便可正确的注入了: 
1Person person = (Person)applicationContext.getBean("person");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值