如何通过自动装配注入具有不同配置的不同ObjectMappers?

问题描述 投票:0回答:2

我正在尝试使用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!
    }
}

但是,似乎两个ObjectMapperstandardObjectMapperspecialObjectMapper都使用相同的StandardProductSerializer

我期望specialObjectMapper使用SpecialProductSerializer,但事实并非如此。

两个ObjectMappers应该不同吗?我假设注入将基于它们的个人名称,因为它们的类型相同?

我应该怎么做才能解决此问题,以便2个ObjectMappers可以使用不同的序列化器?

java spring spring-boot jackson
2个回答
0
投票

添加@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;
}

0
投票

您可以使用@Qualifier批注:


0
投票

您可以使用@Qualifier批注以区分ObjectMapper的不同距离。 (请参阅:https://www.baeldung.com/spring-qualifier-annotation

© www.soinside.com 2019 - 2024. All rights reserved.