作用:Spring中我们可以使用属性编辑器来`将特定的字符串转换为对象`
通过set注入时,想简单的这种是spring提供好了属性编辑器,将value="20"中的字符串转换成了int类型的20
<property name="age" value="20"></property>
但是像下面的这种,value="甘肃兰州",spring是没办法自动将字符串转为Address类型,所以需要我们
自己手动的去写属性编辑器
<property name="address" value="甘肃兰州"></property>
java.beans.PropertyEditor(JDK中的接口)用于将xml文件中字符串转换为特定的类型,同时JDK为我
们提供一个实现类java.beans.PropertyEditorSupport
Student.java
@Data
public class Student {
private long id;
private String name;
private boolean gender;
private int age;
private Address address;//要引入Address类型
}
Address.java
@Data
public class Address {
private String city;
private String street;
private String country;
}
PropertyEditorSupport.java
一定要继承PropertyEditorSupport类,重写里面的setAsText()方法
import java.beans.PropertyEditorSupport;
//一定要继承PropertyEditorSupport类,重写里面的方法
public class AddressEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
//"江苏,昆山,浦东软件园"
String[] str = text.split(","); //按照自己的规则是什么符号分割xml里面传过来的value值
String city = str[0];
String street = str[1];
String country = str[2];
Address add = new Address(city, street, country);
//把新的值设置到对象中
setValue(add);//setValue我们不需要管,直接调用
}
}
proEdit.xml
之前是这样的<property name="address" ref="add"></property>
,通过ref注入,
现在是将<property name="address" value="江苏,昆山,浦东软件园" ></property>"
识别成一个Address
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<bean name="student" class="com.briup.ioc.proEdit.Student">
<property name="id" value="1"></property>
<property name="name" value="tom"></property>
<property name="gender" value="true"></property>
<property name="age" value="20"></property>
<property name="address" value="江苏,昆山,浦东软件园" ></property>
</bean>
</beans>
测试类:
@Test
//知识点: 使用自定义属性编辑器
public void ioc_proEdit() {
try {
String[] path = {"com/briup/ioc/proEdit/proEdit.xml"};
ApplicationContext container = new ClassPathXmlApplicationContext(path);
Student stu=(Student) container.getBean("student");
System.out.println(stu.getAddress());
} catch (Exception e) {
e.printStackTrace();
}
}
结果:可以通过Student拿到Address对象