Spring- 自定义属性编辑器
作者:生
- 2023-10-09 上海
本文字数:1459 字
阅读完需:约 5 分钟
/**
* 自定义属性编辑器
* <p>
* 例如:shanghai_huangpu_huangpu -> Address.class
*/
public class SelfEditor {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("selfEditor.xml");
Customer customer = context.getBean(Customer.class);
System.out.println(customer);
}
}
/**
* 自定义属性编辑器
*/
class AddressPropertyEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
String[] strings = text.split("_");
// 省略校验步骤
Address address = new Address().setProvince(strings[0]).setCity(strings[1]).setTown(strings[2]);
this.setValue(address);
}
}
/**
* 注册自定义属性编辑器
*/
class AddressPropertyEditorRegister implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Address.class, new AddressPropertyEditor());
}
}
class Customer {
private String name;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", address=" + address +
'}';
}
}
class Address {
private String province;
private String city;
private String town;
public String getProvince() {
return province;
}
public Address setProvince(String province) {
this.province = province;
return this;
}
public String getCity() {
return city;
}
public Address setCity(String city) {
this.city = city;
return this;
}
public String getTown() {
return town;
}
public Address setTown(String town) {
this.town = town;
return this;
}
@Override
public String toString() {
return "Address{" +
"province='" + province + '\'' +
", city='" + city + '\'' +
", town='" + town + '\'' +
'}';
}
}
复制代码
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="costomer" class="com.learn.Customer">
<property name="name" value="cyan"/>
<property name="address" value="xx省_xx市_xx区"/>
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<!--<list>
<bean class="com.learn.AddressPropertyEditorRegister"/>
</list>-->
<array>
<bean class="com.learn.AddressPropertyEditorRegister"/>
</array>
</property>
</bean>
</beans>
复制代码
测试输出:Customer{name='cyan', address=Address{province='xxʡ', city='xx��', town='xx��'}}
划线
评论
复制
发布于: 刚刚阅读数: 6
![用户头像](http://static001.geekbang.org/account/avatar/00/18/ee/da/a89757ae.jpg?x-oss-process=image/resize,w_200,h_200)
生
关注
还未添加个人签名 2019-08-17 加入
还未添加个人简介
评论