title: Configuring a Conversion Service with a custom DateFormatter
body: <p>I'm trying to add a custom DateFormatter to my spring/thymeleaf application, with the help of the following documentation :
  <a href="http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#conversions-utility-object" rel="nofollow">http://www.thymeleaf.org/doc/html/Thymeleaf-Spring3.html#conversions-utility-object</a></p>
  
  <p>The problem is that I don't use xml configuration for my beans definitions, but a WebConfig.java class with the following implementation :</p>
  
  <pre><code>@Configuration
  @EnableWebMvc
  @ComponentScan(basePackages = {"com.myapp.web.controller","net.atos.wfs.wts.adminportal.web.domain"})
  public class WebConfig extends WebMvcConfigurerAdapter {
  
  private static final Logger LOG = LoggerFactory.getLogger(WebConfig.class);
  
  
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
      registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
  }
  
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
      LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
      localeChangeInterceptor.setParamName("lang");
      registry.addInterceptor(localeChangeInterceptor);
  }
  
  @Bean
  public LocaleResolver localeResolver() {
      CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
      cookieLocaleResolver.setDefaultLocale(StringUtils.parseLocaleString("en"));
      return cookieLocaleResolver;
  }
  
  @Bean
  public ServletContextTemplateResolver templateResolver() {
      ServletContextTemplateResolver resolver = new ServletContextTemplateResolver();
      resolver.setPrefix("/WEB-INF/views/");
      resolver.setSuffix(".html");
      //NB, selecting HTML5 as the template mode.
      resolver.setTemplateMode("HTML5");
      resolver.setCacheable(false);
      return resolver;
  
  }
  
  public SpringTemplateEngine templateEngine() {
      SpringTemplateEngine engine = new SpringTemplateEngine();
      engine.setTemplateResolver(templateResolver());
      engine.setMessageResolver(messageResolver());
      engine.addDialect(new LayoutDialect());
      return engine;
  }
  
  @Bean
  public ViewResolver viewResolver() {
  
      ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
      viewResolver.setTemplateEngine(templateEngine());
      viewResolver.setOrder(1);
      viewResolver.setViewNames(new String[]{"*"});
      viewResolver.setCache(false);
      return viewResolver;
  }
  
  @Bean
  public IMessageResolver messageResolver() {
      SpringMessageResolver messageResolver = new SpringMessageResolver();
      messageResolver.setMessageSource(messageSource());
      return messageResolver;
  }
  
  @Override
  public void addFormatters(FormatterRegistry registry) {
      super.addFormatters(registry);
      registry.addFormatter(new DateFormatter());
  }
  
  @Bean
  public MessageSource messageSource() {
  
      ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
      messageSource.setBasename("/WEB-INF/messages/messages");
      // if true, the key of the message will be displayed if the key is not
      // found, instead of throwing a NoSuchMessageException
      messageSource.setUseCodeAsDefaultMessage(true);
      messageSource.setDefaultEncoding("UTF-8");
      // # -1 : never reload, 0 always reload
      messageSource.setCacheSeconds(0);
      return messageSource;
  }
  
   }
  </code></pre>
  
  <p>And here is the code of my Custom DateFormatter :</p>
  
  <pre><code>public class DateFormatter implements Formatter&lt;Date&gt; {
  
      @Autowired
      private MessageSource messageSource;
  
  
      public DateFormatter() {
          super();
      }
  
      public Date parse(final String text, final Locale locale) throws ParseException {
          final SimpleDateFormat dateFormat = createDateFormat(locale);
          return dateFormat.parse(text);
      }
  
      public String print(final Date object, final Locale locale) {
          final SimpleDateFormat dateFormat = createDateFormat(locale);
          return dateFormat.format(object);
      }
  
      private SimpleDateFormat createDateFormat(final Locale locale) {
  
          //The following line is not working (nullPointerException on messageSource)
          //final String format = this.messageSource.getMessage("date.format", null, locale);
          //The following line is working :
          final String format = "dd/MM/yyyy";
          final SimpleDateFormat dateFormat = new SimpleDateFormat(format);
          dateFormat.setLenient(false);
          return dateFormat;
      }
  
  }
  </code></pre>
  
  <p><strong>My question is : how can I add a custom formatter that will be able to use @Autowired elements ?</strong></p>
  
  <p>The xml configuration is this one :</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans ...&gt;
  
    ...    
    &lt;mvc:annotation-driven conversion-service="conversionService" /&gt;
    ...
  
    &lt;!-- **************************************************************** --&gt;
    &lt;!--  CONVERSION SERVICE                                              --&gt;
    &lt;!--  Standard Spring formatting-enabled implementation               --&gt;
    &lt;!-- **************************************************************** --&gt;
    &lt;bean id="conversionService"
          class="org.springframework.format.support.FormattingConversionServiceFactoryBean"&gt;
      &lt;property name="formatters"&gt;
        &lt;set&gt;
          &lt;bean class="thymeleafexamples.stsm.web.conversion.VarietyFormatter" /&gt;
          &lt;bean class="thymeleafexamples.stsm.web.conversion.DateFormatter" /&gt;
        &lt;/set&gt;
      &lt;/property&gt;
    &lt;/bean&gt;
  
    ...
  
  &lt;/beans&gt;
  </code></pre>
  
  <p>I tried to uset the following configuration in WebConfig class :</p>
  
  <pre><code>@Bean
      public FormattingConversionServiceFactoryBean conversionService() {
          FormattingConversionServiceFactoryBean conversionService = new FormattingConversionServiceFactoryBean();
          Set&lt;Formatter&lt;?&gt;&gt; formatters = new TreeSet&lt;Formatter&lt;?&gt;&gt;();
          formatters.add(new DateFormatter());
          conversionService.setFormatters(formatters);
          return conversionService;
      }
  </code></pre>
  
  <p>But in this case, the formatter is not taken into account in my application.</p>
  
  <p>Thanks in advance,
  Antoine.</p>