2015-04-28 36 views
3

我有一個自定義轉換器,需要使用少量依賴項。由於轉換器是由JPA管理的,所以我無法找到一種將依賴關係從另一個組件(如依賴注入器)傳遞給其他組件的方法。有沒有這樣的方式?有沒有辦法將依賴關係傳遞給JPA轉換器?

@Converter 
public class CompressingJsonConverter implements AttributeConverter<CompressedJson, Byte[]> { 

    private final Compressing compressing; 
    private final ObjectMapper objectMapper; 

    public CompressingJsonConverter() { 
     // I would like to inject those dependencies instead 
     compressing = new Compressing(); 
     objectMapper = new ObjectMapper(); 
    } 

回答

0

嘗試使用靜態字段。你的DI框架支持靜態注入(我知道Guice和Salta是這樣做的),或者你必須在啓動過程中手工完成。考慮在工具類中註冊注入器(Guice,Salta)或實例(JavaEE/CDI),並從任何需要的地方使用它。

0

您可以嘗試將實用程序類用作單例。從你的問題,我想你有一種依賴注入系統。

如果你能確保該實用程序的對象將被完全初始化之前,你的轉換器類使用它,如果你的DI系統允許調用注射後的初始化方法(春季做),你可以有類似:

class Util { 
    @Inject // or whatever you use for injection 
    private Compressing compressing; 
    @Inject // or whatever you use for injection 
    private ObjectMapper objectMapper; 
    // getters and setters omitted for brevity 

    private static Util instance; 
    public Util getInstance() { 
     return instance; 
    } 

    // DI initialization method after attributes have been injected 
    public void init() { 
     instance = this; 
    } 
} 

然後,您可以做您的轉換器:

@Converter 
public class CompressingJsonConverter implements 
     AttributeConverter<CompressedJson, Byte[]> { 

    private Compressing compressing = null; 
    private ObjectMapper objectMapper = null; 

    private Compressing getCompressing() { 
     if (compressing == null) { 
      // load it first time from util, then caches it locally 
      compressing = Util.getInstance().getCompressing(); 
     } 
     return compressing; 
    } 
    // same for objectMapper 
    ... 
} 

和轉換器一致地使用getCompressing()getObjectMapper

如果您確信該轉換器將永遠不會被構造的Util實例已完全初始化之前,你可以做初始化在構造函數中:

public CompressingJsonConverter() { 
    // I would like to inject those dependencies instead 
    compressing = Util.getInstance().getCompressing(); 
    objectMapper = Util.getInstance().getObjectMapper(); 
} 

,但一定要仔細檢查它的工作原理,它在記錄紅色閃爍的字體,因爲它可能會在任何組件的新版本(DI,JPA,Java等)中崩潰。

相關問題