SpringBoot Webflux无法返回application / xml

时间:2019-03-22 18:57:51

标签: java xml spring-boot spring-webflux jackson-dataformat-xml

在我的反应性REST API中,我试图返回一个XML响应。但是,我总是得到一个JSON,即406 NOT_ACCEPTABLE。知道为什么吗?

@RestController
@RequestMapping(path = "/xml", produces = APPLICATION_XML_VALUE)
public class RestApi {
    @GetMapping(path = "/get")
    public Publisher<ResponseEntity> get() {
        return Mono.just(ResponseEntity.ok().contentType(APPLICATION_XML).body(new Datta("test")));
    }

    @PostMapping(path = "/post", consumes = APPLICATION_XML_VALUE)
    public Publisher<ResponseEntity<Datta>> post(@RequestBody Datta datus) {
        datus.setTitle(datus.getTitle() + "!");
        return Mono.just(ResponseEntity.ok().contentType(APPLICATION_XML).body(datus));
    }
}
  

java.lang.AssertionError:   预期的:application / xml   实际:application / json; charset = UTF-8

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id "io.spring.dependency-management" version "1.0.7.RELEASE"
}
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.8"
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

这些是我的REST controllerunit test的链接。谢谢!

1 个答案:

答案 0 :(得分:2)

显然,jackson-dataformat-xml does not yet支持WebFlux中的XML编组。到目前为止,我看到了两种可能性:

  1. 在类路径上添加org.springframework.boot:spring-boot-starter-web(应该同时有 starter-web starter-webflux )。但是,这仅适用于Servlet 3.1运行时(例如Tomcat)。
  2. 或者如果您希望使用成熟的反应式Web服务器(例如Netty)从{Jaxb2XmlEncoderJaxb2XmlDecoder开始的JAXB编组的use xml:

build.gradle

sourceCompatibility = '11'

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-webflux'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'

    // Java 11 removed these Java EE modules
    implementation "javax.xml.bind:jaxb-api:2.3.1"
    implementation "com.sun.xml.bind:jaxb-core:2.3.0.1"
    implementation "com.sun.xml.bind:jaxb-impl:2.3.2"

    compileOnly "org.projectlombok:lombok"
    annotationProcessor "org.projectlombok:lombok"
}

POJO

@Data
@AllArgsConstructor
@NoArgsConstructor
@XmlRootElement
public class Datta {
    private String title;
}

注意3个javax.xml.bind依赖项(Java 8不需要这些依赖项)和@XmlRootElement批注。该解决方案可以立即生效,但是,如果您要进一步定制,请实施自己的WebFluxConfigurer

@Configuration
@EnableWebFlux
public class WebConfig implements WebFluxConfigurer {
    @Override
    public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
        configurer.registerDefaults(false);
        configurer.customCodecs().decoder(new Jaxb2XmlDecoder());   // <- here
        configurer.customCodecs().encoder(new Jaxb2XmlEncoder());   // <- here

    }
}

Here是源代码的链接。