spring自定义属性编辑器CustomEditorConfig
2016-12-13 本文已影响0人
holly_wang_王小飞
canal源码中自定义了SocketAddressEditor,用于解析private InetSocketAddress address属性 因为配置文件只能配置string类型的字符串 你要将其直接转成对应的实体类肯定会报错。我们可以根据自己的需求自定义解析类
看下SocketAddressEditor是怎么写的
public class SocketAddressEditor extends PropertyEditorSupport implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(InetSocketAddress.class, this);
}
public void setAsText(String text) throws IllegalArgumentException {
String[] addresses = StringUtils.split(text, ":");
if (addresses.length > 0) {
if (addresses.length != 2) {
throw new RuntimeException("address[" + text + "] is illegal, eg.127.0.0.1:3306");
} else {
setValue(new InetSocketAddress(addresses[0], Integer.valueOf(addresses[1])));
}
} else {
setValue(null);
}
}
}
首先继承 PropertyEditorSupport 类覆写方法setAsText() 然后实现接口PropertyEditorRegistrar 的registerCustomEditors方法。该方法是将自定义属性编辑器注册到spring中。然后配置xml
<bean id="socketAddressEditor" class="com.alibaba.otter.canal.instance.spring.support.SocketAddressEditor" />
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<ref bean="socketAddressEditor" />
</list>
</property>
</bean>
canal就是这么做的。其实还有另一种方式就是配置到xml文件中
例如
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.net.InetSocketAddress">
<bean class="com.alibaba.otter.canal.instance.spring.support.SocketAddressEditor">
</bean>
</entry>
</map>
</property>