无法使用 spring 框架在请求映射中获取不同的内容类型?

bra*_*orm 2 spring spring-mvc spring-restcontroller spring-rest

这是我的控制器类:

@Controller
@RequestMapping("/actuator")
public class HealthController {

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON)
    @ResponseBody
    public HealthModel getDump() throws JsonProcessingException {
        return new HealthModel();
        //return mapper.writeValueAsString(metrics.invoke());
    }

    @RequestMapping(value = "/metrics", method = RequestMethod.GET, produces = MediaType.TEXT_PLAIN)
    @ResponseBody
    public String getHealth() {
        return "HEALTHY";
    }
}
Run Code Online (Sandbox Code Playgroud)

模型

public class HealthModel {

    @JsonProperty
    private String status;
    @JsonProperty
    private int id;

    public HealthModel(){
        this.status="WARN";
        this.id=2;
    }

}
Run Code Online (Sandbox Code Playgroud)

注意我已经映射/metrics到返回jsonplain-text取决于Accept Header请求中的

当我提出请求时

curl -v -H "Accept: application/json" http://localhost:8080/myapp/actuator/metrics

我在 json 中得到了预期的响应 {"status":"WARN","id":2}

但是,当我尝试

curl -v -H "Accept: text/plain" http://localhost:8080/myapp/actuator/metrics

我明白了HTTP/1.1 406 Not Acceptable

编辑

@EnableWebMvc
@Configuration
public class AppMvcConfig extends WebMvcConfigurerAdapter {

   @Resource(name = "appObjectMapper")
    private ObjectMapper appObjectMapper;

    @Resource(name = "modelObjectMapper")
    private ObjectMapper modelObjectMapper;

 @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        final MappingJackson2HttpMessageConverter inputConverter = new MappingJackson2HttpMessageConverter();
        inputConverter.setObjectMapper(appObjectMapper);

        final MappingJackson2HttpMessageConverter outputConverter = new MappingJackson2HttpMessageConverter();
        outputConverter.setObjectMapper(modelObjectMapper);

        converters.add(new JacksonDualMapperConverter(appObjectMapper, modelObjectMapper));

        super.configureMessageConverters(converters);
    }

}
Run Code Online (Sandbox Code Playgroud)

小智 6

以防万一有人仍然收到Type mismatch: cannot convert from MediaType to String[]错误:

解决方案是使用 MediaType.APPLICATION_JSON_VALUE

代替 MediaType.APPLICATION_JSON

问候