canal源碼中自定義了SocketAddressEditor绷雏,用于解析private InetSocketAddress address屬性 因?yàn)榕渲梦募荒芘渲胹tring類型的字符串 你要將其直接轉(zhuǎn)成對(duì)應(yīng)的實(shí)體類肯定會(huì)報(bào)錯(cuò)曹动。我們可以根據(jù)自己的需求自定義解析類
看下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() 然后實(shí)現(xiàn)接口PropertyEditorRegistrar 的registerCustomEditors方法。該方法是將自定義屬性編輯器注冊(cè)到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就是這么做的。其實(shí)還有另一種方式就是配置到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>