【发布时间】:2020-09-24 16:19:59
【问题描述】:
我试图强制 SpringBoot 使用 Gson 而不是 Jackson。我已经阅读了我在网上找到的大部分文章,但我仍然看到杰克逊被使用。这就是我所做的
- 已添加
spring:
http: { converters: { preferred-json-mapper: gson } }
mvc: { converters: {preferred-json-mapper: gson } }
在 application.yaml 中
- 更新了 POM
- 添加了
gson依赖 - 将
jackson-databind添加到spring-boot-starter-web依赖项的排除列表中。
- 添加了
- 在主类中添加了
@EnableAutoConfiguration(exclude = JacksonAutoConfiguration.class)。 - 写在
@Configuration类下面:
@Configuration
@Slf4j
public class MyConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters (List<HttpMessageConverters<?>> converters) {
log.debug("Setting gson converter");
converters.add(new GsonHttpMessageConverter(myCustomGsonInstance()));
}
public Gson myCustomGsonInstance() {
return new Gson();
}
}
在调试中运行测试时,我可以看到 Jackson 仍然列在 HttpMessageConverters 列表中,而 Gson 没有。
更新: 在实时运行和以下测试类中会看到此行为。
@AutoConfigureMockMvc
@SpringBootTest(webEnvironment = MOCK)
@ExtendWith(MockitoExtension.class)
public class MyTestClass {
@Autowired
private MyController controller;
private MockMvc mockMvc;
@BeforeEach
public void setUp(){
mockMvc = MockMvcBuilders.standaloneSetup(controller)
// .setMessageConverters(new GsonHttpMessageConverter(myCustomGsonInstance())) // if I add this, the test passes.
.build();
}
@Test
public void happyFlow(){
// given
URI uri = "/test/uri";
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
// when
String responseBody = mockMvc.perform(get(uri).headers(headers)).andReturn().getResponse().getContentAsString();
// then
assertThat(responseBody, wasSerializedByGson());
}
}
【问题讨论】:
-
当你不是从测试运行时(我的意思是在调试模式下启动应用程序,你会看到什么)?还请显示测试的骨架,根据注释的不同,它的行为可能会有所不同?
-
你的
myCustomGsonInstance()来自哪里?这已经是 ApplicationContext 中的 bean 了吗? -
只是同一个类中的一个方法,它返回一个 Gson 的实例。为清晰起见进行了更新。
-
为什么要手动配置
MockMvc你应该在MockMvc上使用@Autowired。
标签: spring-boot gson