如何通过自动装配注入具有不同配置的不同ObjectMappers?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何通过自动装配注入具有不同配置的不同ObjectMappers?相关的知识,希望对你有一定的参考价值。
我正在尝试使用2个不同的Jackson ObjectMapper
,以便我可以在我的代码中使用它们之一进行切换。 2个ObjectMapper
的配置将略有不同。
在我的配置文件中,通过这种方式,我将它们作为2种单独的方式表示:
@Configuration
public class ApplicationConfiguration {
private ObjectMapper createMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
// And a few more other common configurations
return mapper;
}
@Bean
public ObjectMapper standardObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Product.class, new StandardProductSerializer());
mapper.registerModule(module);
return mapper;
}
@Bean
public ObjectMapper specialObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
// In this mapper, I have a different serializer for the Product class
module.addSerializer(Product.class, new SpecialProductSerializer());
mapper.registerModule(module);
return mapper;
}
}
我的计划是在需要时注入并使用这些映射器之一。所以在我的测试中,我有这样的东西:
class SerializationTest {
@Autowired
private ObjectMapper standardObjectMapper;
@Autowired
private ObjectMapper specialObjectMapper;
@Test
void testSerialization() throws JsonProcessingException {
Product myProduct = new Product("Test Product");
String stdJson = objectMapper.writeValueAsString(myProduct);
String specialJson = specialObjectMapper.writeValueAsString(myProduct);
// Both stdJson and specialJson are of the same value even though they should be different because the mappers have different serializers!
}
}
但是,似乎两个ObjectMapper
,standardObjectMapper
和specialObjectMapper
都使用相同的StandardProductSerializer
。
我期望specialObjectMapper
使用SpecialProductSerializer
,但事实并非如此。
两个ObjectMappers应该不同吗?我假设注入将基于它们的个人名称,因为它们的类型相同?
我应该怎么做才能解决此问题,以便2个ObjectMappers可以使用不同的序列化器?
答案
添加@Qualifier
应该可以解决您的问题
@Bean
@Qualifier("standardMapper")
public ObjectMapper standardObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Product.class, new StandardProductSerializer());
mapper.registerModule(module);
return mapper;
}
@Bean
@Qualifier("specialMapper")
public ObjectMapper specialObjectMapper() {
ObjectMapper mapper = createMapper();
SimpleModule module = new SimpleModule();
// In this mapper, I have a different serializer for the Product class
module.addSerializer(Product.class, new SpecialProductSerializer());
mapper.registerModule(module);
return mapper;
}
另一答案
您可以使用@Qualifier
批注:
另一答案
您可以使用@Qualifier
批注以区分ObjectMapper的不同距离。 (请参阅:https://www.baeldung.com/spring-qualifier-annotation)
以上是关于如何通过自动装配注入具有不同配置的不同ObjectMappers?的主要内容,如果未能解决你的问题,请参考以下文章