Ⅵ.spring的点点滴滴--自定义类型转换器
承接上文
自定义类型转换器
.net篇(环境为vs2012+Spring.Core.dll v1.31)
public class CustomeConverter : TypeConverter{ public override bool CanConvertFrom( ITypeDescriptorContext context, Type sourceType){ return true; } public override object ConvertFrom( ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value){ return new TypeCunstomer() { Name = value.ToString() }; } } public class TypeObject{ public TypeCunstomer Name { get; set; } } public class TypeCunstomer{ public string Name { get; set; } }
<object type="Spring.Objects.Factory.Config.CustomConverterConfigurer, Spring.Core"> <property name="CustomConverters"> <dictionary> <entry key="SpringBase.TypeCunstomer"> <object type="SpringBase.CustomeConverter"/> </entry> </dictionary> </property> </object> <object id="typeconvert" type="SpringBase.TypeObject,SpringBase"> <property name="Name" value="2"/> </object>
- 继承中的CanConvertFrom方法是用于判断能否转换,ConvertFrom转换的具体方法
java篇(环境为Maven+Jdk1.7+IntelliJ IDEA 12.1.4)
package springdemo; import java.beans.PropertyEditorSupport; public class TypeObject { private TypeCunstomer name; public TypeCunstomer getName() { return name; } public void setName(TypeCunstomer name) { this.name = name; } } class TypeCunstomer { private String name; String getName() { return name; } void setName(String name) { this.name = name; } } class CustomeConverter extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { TypeCunstomer val=new TypeCunstomer(); val.setName(text+"Convent"); this.setValue(val); } }
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="springdemo.TypeCunstomer"> <bean class="springdemo.CustomeConverter" /> </entry> </map> </property> </bean> <bean id="typeObject" class="springdemo.TypeObject"> <property name="name" value="1"/> </bean>
- 重写setAsText方法,其中setValue的参数为object
java和Csharp的共同点
- 配置文件中的dictionary|map标签设置的key为要转换的类型,值为转换的方法类
- 都是继承一个对象,然后重写方法来自定义类型的转换
作者:cnljli
欢迎转载,但还请尊重劳动果实,保留此段声明并注明原文链接。