Search code examples
javaspringspring-data-restspring-rest

How to set the default media type for spring-data-rest?


From RepositoryRestConfiguration I can see that setting spring.data.rest.default-media-type=application/json could change the default media type served by @RepositoryRestResource.

@SuppressWarnings("deprecation")
public class RepositoryRestConfiguration {
    private MediaType defaultMediaType = MediaTypes.HAL_JSON;
}

Question: as this class is in deprecation, what is the correct way to set/override the default type?


Solution

  • You can do this via RepositoryRestConfiguration or simply with a property in your application.properties. See the documentation here.

    The RepositoryRestConfiguration class is NOT deprecated. There are methods within it that are deprecated. The @SuppressWarnings("deprecation") annotation on the class does not mean that the class itself is deprecated. That is simply an annotation used to tell an IDE to not display deprecation warnings in the IDE.

    The easiest way to do this would be in application.properties. However, you have the property name wrong. You wouldn't set it as spring.data.rest.default-media-type. The actual property it would expect is spring.data.rest.defaultMediaType. So in your application.properties, you could have:

    spring.data.rest.defaultMediaType=application/json
    

    With the RepositoryRestConfiguration, you could accomplish the same as such:

    @Configuration
    class CustomRestMvcConfiguration {
    
      @Bean
      public RepositoryRestConfigurer repositoryRestConfigurer() {
    
        return new RepositoryRestConfigurerAdapter() {
    
          @Override
          public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
            config.setDefaultMediaType(MediaType.APPLICATION_JSON);
          }
        };
      }
    }