【发布时间】:2016-03-13 10:26:01
【问题描述】:
我已经使用自定义 Jackson 模块(使用 Spring Boot 1.3)在 Spring REST 文档上编写了一个小测试。在我的应用程序主类中,我只有@SpringBootApplication。然后我有另一个类JacksonCustomizations,看起来像这样:
@Configuration
public class JacksonCustomizations {
@Bean
public Module myCustomModule() {
return new MyCustomModule();
}
static class MyCustomModule extends SimpleModule {
public MyCustomModule() {
addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
@Override
public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
}
});
}
}
}
这种定制是完美的。当我运行 Spring Boot 应用程序时,我看到了应有的 JSON。
但是,在我的文档测试中,没有应用自定义。这是我的测试代码:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@WebAppConfiguration
public class NoteControllerDocumentation {
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(documentationConfiguration(restDocumentation))
.build();
}
@Test
public void notesListExample() throws Exception {
mockMvc.perform(get("/api/notes/"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(document("notes-list-example", responseFields(
fieldWithPath("[]").description("An array of <<note-example,note>>s."))));
}
@Configuration
@EnableWebMvc
@Import(JacksonCustomizations.class)
public static class TestConfiguration {
@Bean
public NoteController noteController() {
return new NoteController();
}
}
}
注意我的测试中的应用程序上下文如何导入JacksonCustomizations 配置。
我发现的其他东西:
- 在我的启动应用程序中添加
@EnableWebMvc会使自定义停止工作。 - 删除我的测试中的
@EnableWebMvc会停止生成 JSON。
【问题讨论】:
-
您是否尝试将 @Import(JacksonCustomizations.class) 添加到 NoteControllerDocumentation 类?
-
@reos 没有区别
-
听起来 Spring Boot 没有使用您的自定义
Module自动配置ObjectMapper。这与您没有为您的应用程序提供类(es)的SpringApplicationConfiguration的事实相匹配,因此 Spring Boot 不知道该怎么做。事实上,您共享的代码失败并显示IllegalStateException,因为这个原因,“在 @SpringApplicationConfiguration 中找不到配置类或位置”。您能否分享一个包含您正在运行以触发问题的确切代码的小型示例项目? -
ContextConfiguration不是自动使用内部类Configuration吗?请从dl.dropboxusercontent.com/u/6373261/so-34156932.zip下载显示问题的示例项目。 -
啊,不清楚(格式有点不对)
TestConfiguration是一个内部类。感谢您的示例项目。我已经在下面发布了答案。
标签: java spring spring-mvc spring-boot spring-restdocs