属性编辑器就是用于属性值与文本值互相转换的,比如你输入一段文字,使用属性编辑器将其转换成类的属性。每个属性编辑器仅用于某一类属性。
每个属性编辑器都需要继承PropertyEditorSupport类,重写getAsText()方法得到将属性变成文本,重写setAsText()方法得到将文本转换成属性。
比如为User类写一个属性编辑器,可以命名为UserEditor这样可以省去在配置文件中注册的步骤
package com.lkt.entity;
public class User {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
package com.lkt.entity;
import java.beans.PropertyEditorSupport;
public class UserEditor extends PropertyEditorSupport {
@Override
public String getAsText() {
User user=(User) getValue();
return user.getUsername()+","+user.getPassword();
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
String[] strs=text.split(",");
User user=new User();
user.setUsername(strs[0]);
user.setPassword(strs[1]);
setValue(user);
}
}
写一个测试类,类的属性为User类型
package com.lkt.entity;
public class UserTest {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
在配置文件中注册
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="user" class="com.lkt.entity.User"></bean>
<!-- 注册属性编辑器,如果属性编辑器的类名是被编辑的类名+Editor,则可以省略注册 -->
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="com.lkt.entity.User">
<bean class="com.lkt.entity.UserEditor"></bean>
</entry>
</map>
</property>
</bean>
<!-- 注册测试类,user的属性值为一个以逗号分隔的字符串 -->
<bean id="userTest" class="com.lkt.entity.UserTest">
<property name="user">
<value>zhangsan,zhangsan</value>
</property>
</bean>
</beans>
这样我们在获取UserTest类的user属性时,他的username和password将会是zhangsan和zhangsan.