您可以嘗試將實用程序類用作單例。從你的問題,我想你有一種依賴注入系統。
如果你能確保該實用程序的對象將被完全初始化之前,你的轉換器類使用它,如果你的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等)中崩潰。