說明:在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); } }
就是不明白為什么會這樣,雖然是能用,但是未能找到合理的解釋。
參考: