2017-06-29 40 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

相關問題