君子博学而日参省乎己 则知明而行无过矣

博客园 首页 新随笔 联系 订阅 管理
用于属性的转换,是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");
posted on 2012-08-06 23:09  刺猬的温驯  阅读(447)  评论(0编辑  收藏  举报