Spring关于使用注解@Configuration去配置FormattingConversionServiceFactoryBean来实现自定义格式字符串处理无效的问题(未找到是什么原因造成的)

说明:在Spring MVC和Spring Boot中都能正常使用。

首先,我实现了一个自定义的注解,@Trimmed去除字符串String的前后空格。

如果是在Spring MVC的XML配置中,可以这样写:

<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean">  
      <property name="formatters">  
          <list>  
              <bean class="com.benben.timetable.common.formatter.TrimmedAnnotationFormatterFactory"/>  
          </list>  
      </property>  
</bean> 

但是,如果是基于注解类型去配置以上的配置时,我们通常会有以下的几种形式去配置,应该是第一反应会这样去封装:

@Configuration
public class SpringConfig{    
    
    @Bean
    public FormattingConversionServiceFactoryBean conversionService() {         
        FormattingConversionServiceFactoryBean conversionService = new FormattingConversionServiceFactoryBean();
        Set<TrimmedAnnotationFormatterFactory> fromatters = new HashSet<TrimmedAnnotationFormatterFactory>();
        fromatters.add(new TrimmedAnnotationFormatterFactory());
        conversionService.setFormatters(fromatters);
        return conversionService;
    }
    
    @Bean
    public FormattingConversionServiceFactoryBean conversionService() {
        FormattingConversionServiceFactoryBean conversionService = new FormattingConversionServiceFactoryBean();
        Set<TrimmedAnnotationFormatterFactory> formatters = new HashSet<TrimmedAnnotationFormatterFactory>();
        formatters.add(new TrimmedAnnotationFormatterFactory());
        conversionService.setFormatters(formatters);
        return conversionService;
    }
    
    @Bean
    public ConversionService conversionService() {
        DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService( false );
        conversionService.addFormatterForFieldAnnotation(new TrimmedAnnotationFormatterFactory());
        return conversionService;
    }

}

但是很遗憾,以上的方式会正常注入,就是不起作用,完全无效。

经过排查和研究,如果是继承WebMvcConfigurerAdapter来重写addFormatters,然后把自定义的Factory加入进去,那么这样是成功的,也能正常处理,写法如下:

@Configuration
public class SpringConfig extends WebMvcConfigurerAdapter{

    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatterForFieldAnnotation(new TrimmedAnnotationFormatterFactory());
        super.addFormatters(registry);
    }

}

就是不明白为什么会这样,虽然是能用,但是未能找到合理的解释。

 

参考:

https://stackoverflow.com/questions/23062337/configuring-a-conversion-service-with-a-custom-dateformatter

https://github.com/spring-projects/spring-boot/issues/6222

posted @ 2017-09-25 15:58  EasonJim  阅读(9762)  评论(0编辑  收藏  举报