Spring hateoas : Custom media type configuration
Custom media type implementations are picked up by Spring HATEOAS by scanning the application context for any implementations of the HypermediaMappingInformation interface. Each media type must implement this interface in order to:
Be applied to WebClient, WebTestClient, or RestTemplate instances.
Support serving that media type from Spring Web MVC and Spring WebFlux controllers.
To define your own media type could look as simple as this:
@Configuration
class MyMediaTypeConfiguration implements HypermediaMappingInformation {
@Override
public List<MediaType> getMediaTypes() {
return MediaType.parse("application/vnd-acme-media-type")
}
@Override
public Module getJacksonModule() {
return new Jackson2MyMediaTypeModule();
}
@Bean
MyLinkDiscoverer myLinkDiscoverer() {
return new MyLinkDiscoverer();
}
}
The configuration class returns the media type it supports. This applies to both server-side and client-side scenarios.
It overrides getJacksonModule() to provide custom serializers to create the media type specific representations.
It also declares a custom LinkDiscoverer implementation for further client-side support.
The Jackson module usually declares Serializer and Deserializer implementations for the representation model types RepresentationModel, EntityModel, CollectionModel and PagedModel. In case you need further customization of the Jackson ObjectMapper (like a custom HandlerInstantiator), you can alternatively override configureObjectMapper(…).
Prior versions of reference documentation has mentioned implementing the MediaTypeConfigurationProvider interface and registering it with spring.factories. This is NOT necessary. This SPI is ONLY used for out-of-the-box media types provided by Spring HATEOAS. Merely implementing the HypermediaMappingInformation interface and registering it as a Spring bean is all that’s needed.
Comments
Post a Comment