简体   繁体   中英

XML as a default response for Spring Rest

I am using Spring Boot to create REST service which has to return by default application/XML as a response when no Accept header from the client is received. Unfortunately, Spring has as default JSON. How can I switch this default behaviour?

So far I have tried :

Adding this dependency helped to produce XML (but only with Accept header set from client - so no default):

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
</dependency>

Trying to set the default for ContentNegotiationManagerFactoryBean in my @SpringBoot class

 @Bean
  ContentNegotiationManagerFactoryBean contentNegotiationManagerFactoryBean() {
    val myBean = new ContentNegotiationManagerFactoryBean();
    myBean.setDefaultContentType(MediaType.APPLICATION_XML);
    return myBean;
  }

resulted in error :

Method viewResolver in org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter required a single bean, but 2 were found

Trying to exclude it via:

@SpringBootApplication(exclude = { ContentNegotiationManagerFactoryBean.class })

only gives another error:

The following classes could not be excluded because they are not auto-configuration classes

Instead of creating your own ContentNegotiationManagerFactoryBean you could use a ContentNegotiationConfigurer to set up the default content type.

In your WebMvcConfigurerAdapter , override the method configureContentNegotiation() and call the method defaultContentType() on the supplied ContentNegotiationConfigurer . That way, the auto configured ContentNegotiationManager will have that option set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM