【发布时间】:2018-08-29 15:55:56
【问题描述】:
我设置了一个类来返回自定义的 ObjectMapper。据我所知,让 Spring Boot 使用此 ObjectMapper 的正确方法是将其声明为 @Primary,它就是。
@Configuration
public class MyJacksonConfiguration {
@Bean
@Primary
public ObjectMapper objectMapper() {
return Jackson2ObjectMapperBuilder
.json()
.findModulesViaServiceLoader(true)
.mixIn(Throwable.class, ThrowableMixin.class)
.featuresToDisable(
WRITE_DATES_AS_TIMESTAMPS)
.serializationInclusion(
Include.NON_ABSENT)
.build();
}
}
但是,当我从控制器方法返回对象时,它会使用默认的 Jackson ObjectMapper 配置进行序列化。
如果我将一个显式 ObjectMapper 添加到我的控制器并在其上调用 writeValueAsString,我可以看到这个 ObjectMapper 是我希望 Spring Boot 使用的自定义对象。
@RestController
public class TestController {
@Autowired
private TestService service;
@Autowired
private ObjectMapper mapper;
@GetMapping(value = "/test", produces = "application/json")
public TestResult getResult() {
final TestResult ret = service.getResult();
String test = "";
try {
test = mapper.writeValueAsString(ret);
// test now contains the value I'd like returned by the controller!
} catch (final JsonProcessingException e) {
e.printStackTrace();
}
return ret;
}
}
当我在控制器上运行测试时,测试类也使用自动装配的 ObjectMapper。同样,提供给测试的 ObjectMapper 是自定义的。
所以 Spring 在一定程度上知道自定义的 ObjectMapper,但我的 rest 控制器类没有使用它。
我已尝试为 Spring 启用调试日志记录,但在日志中看不到任何有用的信息。
知道可能会发生什么,或者我应该在哪里寻找问题?
编辑:似乎有多种方法可以做到这一点,但是我尝试这样做的方式似乎是一种推荐的方法,我想让它以这种方式工作 -请参阅https://docs.spring.io/spring-boot/docs/1.4.7.RELEASE/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper 中的 71.3 - 我是否误解了那里的内容?
【问题讨论】:
标签: spring-boot jackson2