Spring Ioc配置类型转换器

本文详细介绍如何在Spring框架中实现自定义属性转换器,通过继承PropertyEditorSupport类并重写setAsText方法,实现字符串到特定类型的转换。示例包括将字符串转换为自定义类型ExoticType及日期类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档 在转换类中继承PropertyEditorSupport 并从写setAsText方法 将处理好的值传入 setValue();
bean方法中固定格式修改map中参数 使用键值对声明配置需要转换的类型 ,转换方法的类路径

public class 转换类 extends PropertyEditorSupport {
    public void setAsText(String text) {
    //处理代码段
        setValue(new ExoticType(text.toUpperCase()));
    }
}


<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
        <map>
        //                 转换的类型                   转换的类路径
            <entry key="example.ExoticType" value="example.ExoticTypeEditor"/>
        </map>
    </property>
</bean>

{

@我们来举个栗子   把String转换成date
public class String2Date extends PropertyEditorSupport
public void setAsText(String text) throws IllegalArgumentException {
	Date date=null;
	SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
	try {
		date = sdf.parse(text);
	} catch (java.text.ParseException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
	setValue(date);
}
 <!--------- 配置属性转换器  修改map标签内的内容 键值对方式key:遇到生么样的类型----------  -->
  <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="customEditors">
        <map>
            <entry key="java.util.Date"  value="comment.String2Date"/>
        </map>
    </property>
  </bean>
 
 <bean id="stu" class="emtity.Student"> 
   <property name="id" value="15"></property>
   <property name="name" value="小明"></property>
   <property name="age"   value="19"></property>
   <property name="brithday" value="1999-12-12"></property>
 </bean>

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值