Spring中的PropertyEditor的简单实用方法

用于属性的转换,是BeanPostProcessor的一种,比如有如下两个java类:
package com.google.spring.applicationContext;

public class Computer
{
	private String name;
	
	public Computer()
	{
		
	}
	
	public Computer(String name)
	{
		this.name = name;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}
	
}

package com.google.spring.applicationContext;

public class Person
{
	private Computer computer ;

	public Computer getComputer()
	{
		return computer;
	}

	public void setComputer(Computer computer)
	{
		this.computer = computer;
	}
	
	
}

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

这时候在getBean("person")的时候是有问题的。通过PropertyEditor 可以将字符串映射为其它类型:
package com.google.spring.applicationContext;

import java.beans.PropertyEditorSupport;

public class ComputerTypeEditor extends PropertyEditorSupport
{
	private String format;

	public String getFormat()
	{
		return format;
	}

	public void setFormat(String format)
	{
		this.format = format;
	}
	
	public void setAsText(String text)
	{
		Computer computer = new Computer(text);
		this.setValue(computer);
	}
}

在XML中注册一下该转换器:
	<bean id="customEditorConfigure" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
	     <property name="customEditors">
	         <map>
	            <entry key="com.google.spring.applicationContext.Computer">
	               <bean class="com.google.spring.applicationContext.ComputerTypeEditor">
	                   <property name="format">
	                       <value>upperCase</value>
	                   </property>
	               </bean>
	            </entry>
	         </map>
	     </property>
	</bean>

这时候便可正确的注入了:
Person person = (Person)applicationContext.getBean("person");


你可能感兴趣的:(Spring中的PropertyEditor的简单实用方法)