package onlyfun.caterpillar;
public class User {
private String name;
private int number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
package onlyfun.caterpillar;依最基本的设定方式,您要在Bean定义档中作以下的设定,以完成依赖注入:
public class HelloBean {
private String helloWord;
private User user;
public HelloBean() {
}
public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
<?xml version="1.0" encoding="UTF-8"?>您可以实作java.beans.PropertyEditor接口,但更方便的是继承 java.beans.PropertyEditorSupport,PropertyEditorSupport实作了PropertyEditor介 面,您可以重新定义它的setAsText()方法,这个方法传入一个字符串值,您可以根据这个字符串值内容来建立一个User对象,例如:
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="userBean" class="onlyfun.caterpillar.User">
<property name="name">
<value>Justin</value>
</property>
<property name="number">
<value>5858588</value>
</property>
</bean>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="user">
<ref bean="userBean"/>
</property>
</bean>
</beans>
package onlyfun.caterpillar;接下来您可以在Bean定义档中这么使用:
import java.beans.PropertyEditorSupport;
public class UserEditor extends PropertyEditorSupport {
public void setAsText(String text) {
String[] strs = text.split(",");
int number = Integer.parseInt(strs[1]);
User user = new User();
user.setName(strs[0]);
user.setNumber(number);
setValue(user);
}
}
<?xml version="1.0" encoding="UTF-8"?>只要是User类型的属性,现在可以使用"Justin,5858588"这样的字符串来设定,CustomEditorConfigurer会加载 customEditors属性中设定的key-value,根据key得知要使用哪一个PropertyEditor来转换字符串值为对象,藉此可以简化 一些Bean属性文件的设定。
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="configBean" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="onlyfun.caterpillar.User">
<bean id="userEditor" class="onlyfun.caterpillar.UserEditor"/>
</entry>
</map>
</property>
</bean>
<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="user">
<value>Justin,5858588</value>
</property>
</bean>
</beans>