Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering a Jackson module for Spring Data REST

I have a working project based on the Spring Data REST example project, and I'm trying to do custom serialization using a Jackson module based on this wiki page.

Here's my Jackson module:

public class CustomModule extends SimpleModule {
    public static Logger logger = LoggerFactory.getLogger(CustomModule.class);

    public CustomModule() {
        super("CustomModule", new Version(1, 0, 0, null));
    }

    @Override
    public void setupModule(SetupContext context) {
        logger.debug("CustomModule.setupModule");
        SimpleSerializers simpleSerializers = new SimpleSerializers();
        simpleSerializers.addSerializer(new CustomDateTimeSerializer());
        context.addSerializers(simpleSerializers);
    }

}

The wiki page says:

Any Module bean declared within the scope of your ApplicationContext will be picked up by the exporter and registered with its ObjectMapper.

I'm still pretty new to Spring, so I might just be putting my module bean definition in the wrong place; currently it's in src/main/resources/META-INF/spring-data-rest/shared.xml, which is imported from repositories-export.xml:

<bean id="customModule" class="org.hierax.wpa.schema.mapping.CustomModule" />

I don't see the log statement in setupModule, but I do see log output for other classes in the same package.

I'm using Spring Data REST 1.0.0.RC2.

like image 943
Mike Partridge Avatar asked Oct 04 '12 03:10

Mike Partridge


2 Answers

Currently, it's possible to customize a module in Spring Boot like this:

@Bean
public Module customModule() {
  return new CustomModule();
}

Reference: Latest Jackson integration improvements in Spring

like image 118
Denis C de Azevedo Avatar answered Oct 17 '22 11:10

Denis C de Azevedo


I've had success using the solution outlined in the wiki entry that you have linked to (although perhaps it has changed since this stack overflow post)

In my instance I was using [email protected]

Your code seems to be correct and provided that your application context is being loaded correctly I don't see any reason for it not to be working.

I've attached my simpler Module which exemplifies the use of a date formatter:

@Component
public class JsonMarshallingConfigModule extends SimpleModule {

  public JsonMarshallingConfigModule() {
    super("JsonMarshallingConfigModule", new Version(1, 0, 0, "SNAPSHOT"));
  }

  @Override public void setupModule(SetupContext context) {
    context.getSerializationConfig().setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'"));
  }
}

Perhaps it can be used to outline if it is infact the jackson module that is the problem or spring-data-rest-mvcweb.

like image 31
Benjamin Conlan Avatar answered Oct 17 '22 11:10

Benjamin Conlan