类型转换器
Spring 通过类型转换器把配置⽂件中字符串类型的数据,转换成了对象中成员变量对应类型的数据,进⽽完成了注⼊。
<bean id="people" class="world.xuewei.entity.People"> <property name="name" value="XW"/> <property name="age" value="25"/> </bean>
package world.xuewei.entity; import java.util.Date; /** * 人实体 * * @author 薛伟 * @since 2023/9/14 17:17 */ public class People { private String name; private Integer age; private Date birthday; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "People{" + "name='" + name + '\'' + ", age=" + age + ", birthday=" + birthday + '}'; } }
自定义类型转换器
对于日期类型的成员变量,我们无法通过默认的类型转换器完成注入,这时候我们就需要自定义类型转化器。
自定义类型转换器需要实现 Converter 接口,FROM 表示转换前的类型,TO 表示转换后的类型。需要实现 convert 方法。
package world.xuewei.convert; import org.springframework.core.convert.converter.Converter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * 自定义日期类型转换器 * * @author 薛伟 * @since 2023/9/14 17:17 */ public class DateConvert implements Converter<String, Date> { private String pattern; public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } @Override public Date convert(String s) { Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(pattern); try { date = sdf.parse(s); } catch (ParseException e) { e.printStackTrace(); } return date; } }
编写好转换器后还需要注册到 Spring 中。
<!-- 创建转换器 --> <bean id="dateConvert" class="world.xuewei.convert.DateConvert" p:pattern="yyyy-MM-dd"/> <!-- ⽤于注册类型转换器 --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <set> <ref bean="dateConvert"/> </set> </property> </bean> <bean id="people" class="world.xuewei.entity.People"> <property name="name" value="XW"/> <property name="age" value="25"/> <property name="birthday" value="1999-07-29"/> </bean>
注意点
- 转换器中的日期格式可以通过注入的方式实现,从而不需要在代码中写死。
- ConversionSeviceFactoryBean 定义 id 属性值必须为 conversionService,这是 Spring 官方的约束。
- Spring 框架其实内置了⽇期类型的转换器,但是格式为 yyyy/MM/dd,不支持自定义格式。如果自定义了日期类型转换器,那么由框架提供的转换器就会失效!