具体demo如下:
public class StringToIntPropertiesEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) throws IllegalArgumentException {
this.setValue(Integer.valueOf(text));
}
public static void main(String[] args) {
StringToIntPropertiesEditor stringToIntPropertiesEditor = new StringToIntPropertiesEditor();
stringToIntPropertiesEditor.setAsText("123");
Object value = stringToIntPropertiesEditor.getValue();
System.out.println(value.getClass().getTypeName());
}
}
写一个demo如下:把properties转换为string
@Component("conversionService")
public class PropertiesToStringConvert implements ConditionalGenericConverter {
@Override
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
return Properties.class.equals(sourceType.getType()) && String.class.equals(targetType.getType());
}
@Override
public Set<ConvertiblePair> getConvertibleTypes() {
return Collections.singleton(new ConvertiblePair(Properties.class, String.class));
}
@Override
public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
Properties properties = (Properties)source;
return properties.toString();
}
}
<util:properties id="context">
<prop key="id">1</prop>
<prop key="name">mercyblitz</prop>
</util:properties>
<bean id="user" class="xxx.UserInfo">
<property name="id" value="1"/>
<property name="name" value="test"/>
<property name="context" ref="context"/>
</bean>
<bean id="convert" class="com.ynhuang.thinking.databinder.convert.PropertiesToStringConvert">
</bean>
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters" ref="convert" />
</bean>
当然在spring中配置convertService除了ConversionServiceFactoryBean,还可以使用ConversionService,ConversionService在beanfactory refresh阶段就已经开始加载了,如果不指定,spring只会初始化默认的转换器,则新加的无效。
最后,只有转换器处理完成之后,才会完成整个的数据绑定,也就是在spring bean实例化完成阶段。