2017-06-29 200 views
1

我正在研究一个中间件 - 应用程序,它将通过RestTemplate接收的值反序列化为来自传统API的json-String(因此,不会影响“其”数据模型,因此需要一些自定义配置为我的objectmapper消费这个api),并且应用程序本身也提供基于legacydata作为json的(部分丰富和合成的)数据的一个restful API。在一个Spring Boot应用程序中使用两个不同配置的ObjectMapper

现在,我的遗产 - 映射 - 班所有构造函数是在时刻分享这样一个共同的结构:

... 
    private ObjectMapper mapper; 

    public MyMapper() { 
     this.mapper = new ObjectMapper(); 
     this.mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); 
     this.mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    } 
    ... 

因为我用杰克逊反序列从legacysystem的JSON。基本上我想用Springs DI Container来重构这个冗余。

所以我试图创建自己的Objectmapper @Component就像是在这个线程一些答案说这只是延伸ObjectMapperConfiguring ObjectMapper in Spring - 让称它为FromLegacyObjectMapper - 而不是在每一个类初始化我的映射器,所以我创建了一个与使用

@Autowired 
private FromLegacyObjectMapper 

(或constructorinjection-equivalent,但为了简单起见..)。 但是这有一些严重的副作用。实际上,由于自动装配覆盖了从我的前端反序列化viewModels时实际需要的弹簧引导标准对象映射器,所以我无法反序列化clientjson以在控制器中查看模型。

我设法得到它运行起来就像这样:

frontend <---> My Api using Standard ObjectMapper <--> viewModel created by consuming legacy-Api-json using FromLegacyObjectMapper 

所以,我肯定会用一个基类为我mappingclasses,只是上面添加到基础构造的代码做,让每一个Mapperclass扩展了这个基础,但实际上我希望找到一种使用弹簧依赖注入容器的方法。我现在没有想法,所以我希望任何人都可以帮助我!

编辑:为了让它更清楚一点,请参阅下面的莫里茨答案和我们在评论中的讨论。我很清楚我能够使用@Qualifier注释,但是如果有一种方法可以将@Qualifier添加到Spring控制器中使用的标准对象映射器,那么这只能解决问题。我会自己做一些研究,但其他答案非常受欢迎。

回答

1

我会尝试在Spring容器中添加两个不同的ObjectMapper。你可以添加这样的事情,比如你的Application类(假设是一个与@SpringBootApplication注释):

@Bean 
@Qualifier("fromLegacy") 
public ObjectMapper fromLegacyObjectMapper() { 

    // create and customize your "from legacy" ObjectMapper here 

    return objectMapper; 
} 

@Bean 
@Qualifier("default") 
public ObjectMapper defaultObjectMapper() { 

    // create your default ObjectMapper here 

    return objectMapper; 
} 

然后你就可以在使用旧的API类似这样的课程注入了“从传统的” ObjectMapper

public class SomeServiceUsingLegacyApi { 

    private final ObjectMapper objectMapper; 

    @Autowired 
    public SomeServiceUsingLegacyApi(@Qualifier("fromLegacy") ObjectMapper objectMapper) { 

     this.objectMapper = objectMapper; 
    } 

    // [...] 
} 

而在其他类,因此使用其他API:

public class SomeServiceUsingOtherApi { 

    private final ObjectMapper objectMapper; 

    @Autowired 
    public SomeServiceUsingOtherApi(@Qualifier("default") ObjectMapper objectMapper) { 

    this.objectMapper = objectMapper; 
    } 

    // [...] 
} 
+0

但我不注入标准objectmapper我对照因为这是在春季内部完成的。所以我没有影响在这里添加限定词,是吗?我一直在。NET世界,如果这听起来有些愚蠢,那么很抱歉;) – Dominik

+0

没有什么能够阻止你将自己的bean添加到你的Spring应用程序上下文中,比如ObjectMapper bean。如果在上下文中有相同类型的不同bean,则可以使用'@ Qualifier'注释来告诉Spring何时使用哪个bean。我想给你举个例子说明一下,但我现在没有足够的时间。您还可以在Craig Walls的“Spring in Action”中找到这方面的很好例子。 – anothernode

+0

哦,我刚刚在上面的评论中真正理解了你的问题,我的例子并没有回答这个问题。我不得不做更多的研究,我自己,对不起... – anothernode

相关问题