自定义转换器
自定义转换器,将 String 转换成 LocalDateTime:
1、实现Converter接口:StringToLocalDateTimeConverter
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
@Override
public LocalDateTime convert(String s) {
final DateTimeFormatter dateTimeFormatter =
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
return LocalDateTime.parse(s, dateTimeFormatter);
}
}
2、在 Spring 的配置文件中配置 conversionService 的 Bean:
<!-- 配置转换器的bean -->
<bean id="myConverter"
class="top.songfang.StringToLocalDateTimeConverter"/>
<!-- 注册转换器 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="myConverter"/>
</set>
</property>
</bean>
3、测试:
定义实体:
// 实体定义
public class User{
private String name;
private LocalDateTime birth;
// Setter/Getter
}
配置:
<bean id="user" class="top.songfang.User">
<property name="birth" value="2020-12-20 12:21:36"/>
<property name="name" value="风生"/>
</bean>
测试:
@Test
public void test() {
final User user = context.getBean(User.class);
System.out.println(user.getTime());
}