我的项目大量使用依赖注入,我非常小心避免服务定位器反模式。所有对象都使用构造函数注入进行结构化,这允许容易识别的依赖项列表。现在我正在构建一个对象,它有一个特殊的“常量”实例,它基本上是静态/单例(考虑像Integer.MinValue这样的例子)。所以我最初的反应是使用静态“getter”方法创建一个静态字段,如果以前没有创建该方法,它将创建该对象的实例。然而,对象本身具有依赖性,所以我对实例化这个“特殊实例”的最佳实践感到困惑。我正在寻找有关如何在这种情况下最好地构造代码的建议,理想情况下无需调用容器来解析依赖关系。一些代码:
public class PressureUnit extends DataUnit {
private static PressureUnit standardAtmosphere;
public static PressureUnit StandardAtmosphere() {
if(standardAtmosphere == null){
standardAtmosphere = new PressureUnit(1013.25); // this line is what is bothering me as I need to resolve other dependencies (have to use new as it's a static method and can't be injected like everywhere else)
}
return standardAtmosphere;
}
@AssistedInject
public PressureUnit(ITimeProvider timeProvider, IUnitProvider unitProvider, @Assisted double value) {
this(timeProvider, unitProvider, value, PressureUnits.hPa);
}
...
}
答案 0 :(得分:0)
我真的没有看到你的代码中有任何问题,因为你没有在这里和那里新建依赖项,现在我说可以给出一些建议: