Spring-第12章、自定义类型转换

1.类型转换器

作用:Spring通过类型转换器把配置文件中字符串类型的数据,转换成了对象中成员对应类型的数据,进而完成注入

在这里插入图片描述

2.自定义类型转换

原因:当Spring内部没有提供特定类型转换器时,而程序员在应用的过程中需要使用,那么就需要程序员自己定义类型转换器
  • 类implements Converter接口
    public class MyDateConverter implements Converter<String, Date> {
   		 /*
   		 convert⽅法作⽤:String ---> Date
   		 SimpleDateFormat sdf = new SimpleDateFormat();
   		
   		 sdf.parset(String) ---> Date
   		 param:source 代表的是配置⽂件中 ⽇期字符串 <value>2020-10-
   		11</value>
   		 return : 当把转换好的Date作为convert⽅法的返回值后,Spring⾃动的
   		为birthday属性进⾏注⼊(赋值)
   		 */
    @Override
    public Date convert(String source) {
    Date date = null;
    try {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    date = sdf.parse(source);
    } catch (ParseException e) {
    e.printStackTrace();
    }
    return date;
    }
   }
  • 在Spring的配置文件中进行配置
    (1)MyDateConverter对象创建出来
<bean id="MyDateConverter" class="xxxx.MyDateConverter"/>

(2)类型转换器的注册

目的:告知Spring框架,我们所创建的MyDateConverter是一个类型转换器
<!--⽤于注册类型转换器-->
   	<bean id="conversionService"
   	class="org.springframework.context.support.ConversionServiceFac
   	toryBean">
   		 <property name="converters">
   			 <set>
   				 <ref bean="myDateConverter"/>
   			 </set>
   		 </property>
   	</bean>

3.细节

  • MyDateConverter中的日期的格式,通过依赖注入的方式,由配置文件完成赋值
   	 public class MyDateConverter implements Converter<String, Date> {
   	 private String pattern;
   	 public String getPattern() {
   	 return pattern;
   	 }
   	 public void setPattern(String pattern) {
   	 this.pattern = pattern;
   	 }
   	 /*
   	 convert⽅法作⽤:String ---> Date
   	 SimpleDateFormat sdf = new
   	SimpleDateFormat();
   	 sdf.parset(String) ---> Date
   	 param:source 代表的是配置⽂件中 ⽇期字符串 <value>2020-10-
   	11</value>
   	 return : 当把转换好的Date作为convert⽅法的返回值后,Spring⾃动的
   	为birthday属性进⾏注⼊(赋值)
   	 */
   	 @Override
   	 public Date convert(String source) {
   	 Date date = null;
   	 try {
   	 SimpleDateFormat sdf = new SimpleDateFormat(pattern);
   	 date = sdf.parse(source);
   	 } catch (ParseException e) {
   	 e.printStackTrace();
   	 }
   	 return date;
   	 }
   	}
<!--Spring创建MyDateConverter类型对象-->
<bean id="myDateConverter"
class="com.baizhiedu.converter.MyDateConverter">
	<property name="pattern" value="yyyy-MM-dd"/>
</bean>
  • ConversionSeviceFactoryBean 定义 id属性 值必须 conversionService
  • Spring框架内置⽇期类型的转换器
Spring框架内置⽇期类型的转换器

猜你喜欢

转载自blog.csdn.net/m0_47298981/article/details/107686126
今日推荐