title: Using Spring MVC how do I add a custom JsonSerializer for a java 8 LocalDateTime?
body: <p>I'm using Spring 4.1.6 to create a RESTful API. I am <em>not</em> using Spring Boot. I don't want to annotate each of my resources with <code>@JsonSerialize(using = MyLocalDateTimeJsonSerializer.class)</code> because it adds a lot of boilerplate. Rather, this should be the default behaviour.</p>
  
  <p>Ideally, I'd like to add some configuration to pick up my custom <code>LocalDateTime</code> serializer that would then be used throughout. I saw an example that made me hopeful that the following would work but it does not.</p>
  
  <pre><code>@Configuration
  @EnableWebMvc
  public class JacksonConfiguration extends WebMvcConfigurerAdapter {
  
      @Override
      public void configureMessageConverters(List&lt;HttpMessageConverter&lt;?&gt;&gt; converters) {
         Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder()
          .serializers(new LocalDateTimeJsonSerializer());
          converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
      }
  
  }
  
  public class LocalDateTimeJsonSerializer extends JsonSerializer&lt;LocalDateTime&gt; {
  
      @Override
      public void serialize(LocalDateTime localDateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
              throws IOException, JsonProcessingException {
          jsonGenerator.writeString("foo");
      }
  
      @Override
      public Class&lt;LocalDateTime&gt; handledType() {
          return LocalDateTime.class;
      }
  
  }
  </code></pre>
  
  <p>I note that Spring loads <code>JSR310Module</code> which calls <code>addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)</code> which is being used. Could it be that this is registered after the one in the example above and so taking preference?</p>
  
  <p>Is there a way that I could have my custom <code>LocalDateTime</code> serializer used throughout the code, without using <code>@JsonSerialize</code>?</p>
  
  <p><strong>EDIT</strong>
  The reason that Spring DI was not picking up the annotation based configuration is because my project had xml based configuration too, which had <code>&lt;mvc:annotation-driven/&gt;</code> declared.</p>
  
  <p>This seemed to override the annotated class. Removing this from the xml, the configuration class, which extended <code>WebMvcConfigurerAdapter</code> was component scanned and utilised.</p>