我正在使用2个常见的包,Immutables和Guice。在运行时发生的第一件事是我将环境和其他来源的设置加载到单例,非不可变的配置类中,让我们称之为MyConfig
,例如,公开一个公共的getSettingX()
方法。
MyConfig myConfig = MyConfig.intialize().create();
String settingX = myConfig.getSettingX();
我有一个抽象的Immutable类,称之为AbstractImmutable
。在实例化时需要根据myConfig.getSettingX()
设置一个字段。
@Value.Immutable
abstract class AbstractImmutable {
abstract String getSettingX(); // Ideally set
}
现在,通常我会使用Guice将MyConfig
注入类中,并且会为AbstractImmutable
类的实现找到一种方法(为了避免每次构建对象时手动必须注入MyConfig
类 - 使用juice来实现全部原因开始,管理我的DI)。但是,由于具体的Immutables类是在编译时生成的,因此它不适用于通常的Guice注入注释。
在Immutables站点上有迹象表明使用构建器包来注释静态工厂方法,但我似乎无法想象如何将它添加到抽象不可变类中。
有人有什么建议吗?
据我所知,在生成的Immutables类本身上没有办法做到这一点(虽然你可以用@InjectAnnotation
做一些有趣的事情),所以你可能在那里运气不好。
即使你是在Guice的幌子下问,你要求的东西让我想起AutoFactory使用的模式,并且应该同样适用。实质上,通过注入工厂来利用Factory Pattern然后工厂将创建Immutable对象。
例如,具体指你的情况,
@Value.Immutable
abstract class ValueObject {
MyConfig getMyConfig();
@Value.Derived
String getSettingX() {
getMyConfig().getSettingX();
}
String getAnotherProperty();
class ValueObjectFactory {
@Inject MyConfig myConfig;
ValueObject create(String anotherProperty) {
return ImmutableValueObject.builder()
.setMyConfig(this.myConfig)
.setAnotherProperty(anotherProperty)
.build();
}
}
}
然后,在应用程序代码中,您将直接注入ValueObjectFactory
并在其上调用create
class SomeApplicationClass {
@Inject ValueObjectFactory factory;
void someMethod() {
ValueObject = factory.create("myString");
// ... do something with the ValueObject
}
}
同样,您可以将工厂定义为构建器,但这将是您必须根据所具有的参数数量做出的决定。