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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM