User.java
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
用到User的类:UserContainer.java
public class UserContainer {
private User user;
public void setUser(User user) {
this.user = user;
}
public void printUser() {
System.out.println(user.getName() + " " + user.getAge());
}
}
将配置中的转换的类:TransformUser.java
import java.beans.PropertyEditorSupport;
public class TransformUser extends PropertyEditorSupport {
public void setAsText(String text) {
String[] data = text.split(",");
User user = new User();
user.setName(data[0]);
user.setAge(Integer.parseInt(data[1]));
this.setValue(user);
}
}
测试类:SpringTest.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
ApplicationContext beanFactory = new ClassPathXmlApplicationContext(
"applicationContext.xml");
UserContainer ut = (UserContainer) beanFactory.getBean("userContainer");
ut.printUser();
}
}
需要这样配置:在applicationContext.xml文件中。
<bean id="user" class="User" />
<bean id="userContainer" class="UserContainer">
<property name="user" value="liming,23"></property>
</bean>
<bean id="transformUser" class="TransformUser"></bean>
<bean id="configBean"
class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="User" value-ref="transformUser"></entry>
</map>
</property>
</bean>
将liming,23这种格式的转换成User类。