自定义转换器

自定义转换器,将 String 转换成 LocalDateTime:
1、实现Converter接口:StringToLocalDateTimeConverter

  1. public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
  2. @Override
  3. public LocalDateTime convert(String s) {
  4. final DateTimeFormatter dateTimeFormatter =
  5. DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  6. return LocalDateTime.parse(s, dateTimeFormatter);
  7. }
  8. }

2、在 Spring 的配置文件中配置 conversionService 的 Bean:

  1. <!-- 配置转换器的bean -->
  2. <bean id="myConverter"
  3. class="top.songfang.StringToLocalDateTimeConverter"/>
  4. <!-- 注册转换器 -->
  5. <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  6. <property name="converters">
  7. <set>
  8. <ref bean="myConverter"/>
  9. </set>
  10. </property>
  11. </bean>

3、测试:

定义实体:

  1. // 实体定义
  2. public class User{
  3. private String name;
  4. private LocalDateTime birth;
  5. // Setter/Getter
  6. }

配置:

  1. <bean id="user" class="top.songfang.User">
  2. <property name="birth" value="2020-12-20 12:21:36"/>
  3. <property name="name" value="风生"/>
  4. </bean>

测试:

  1. @Test
  2. public void test() {
  3. final User user = context.getBean(User.class);
  4. System.out.println(user.getTime());
  5. }