gpt4 book ai didi

java - 谷歌指南 : use injected factory to instantiate multiple objects in a class?

转载 作者:行者123 更新时间:2023-11-30 08:43:26 25 4
gpt4 key购买 nike

public class AppModule extends AbstractModule {
@Override
protected void configure() {
install(new FactoryModuleBuilder().implement(BaseClass.class, ImplementingClass.class).build(FactoryClass.class));
}
}

public class AnotherClass {
@Inject
private FactoryClass factoryClass;

private BaseClass firstBaseObject = factoryClass.create("some_parameter");
private BaseClass secondBaseObject = factoryClass.create("another_parameter");

public void processSomething() {
// ... do something that requires both firstBaseObject and secondBaseObject to already be initialized on each call
}
}

有没有办法让我在每次调用 processSomething() 时都可以访问 firstBaseObjectsecondBaseObjectprocessSomething() 的每次调用都依赖于这两个已经实例化的对象,它们是具有大量元数据的巨大对象。即我能否以某种方式确保 factoryClass 在命中这两行时已经实例化?:

    private BaseClass firstBaseObject = factoryClass.create("some_parameter");
private BaseClass secondBaseObject = factoryClass.create("another_parameter");

由于 factoryClass 为空,我在这两行中收到 NullPointerExceptions。

如果您需要更多信息,请告诉我,非常感谢!

最佳答案

使用下面的代码

public class AnotherClass {
private final BaseClass firstBaseObject;
private final BaseClass secondBaseObject;

@Inject
public AnotherClass(FactoryClass factoryClass) {
firstBaseObject = factoryClass.create("some_parameter");
secondBaseObject = factoryClass.create("another_parameter");
}

public void processSomething() {
// ... do something that requires both firstBaseObject and secondBaseObject to already be initialized on each call
}
}

不能使用字段或方法注入(inject),因为 factoryClass 中的注入(inject)是在填充 firstBaseObject 和 secondBaseObject 之后进行的。

public class AppModule extends AbstractModule {
@Override
protected void configure() {
...
bind(BaseClass.class)
.annotatedWith(Names.named("firstBaseObject"))
.toInstance(factoryClass.create("some_parameter"));

bind(BaseClass.class)
.annotatedWith(Names.named("secondBaseObject"))
.toInstance(factoryClass.create("another_parameter"));
}
}

public class AnotherClass {
@Inject
@Named("firstBaseObject")
private BaseClass firstBaseObject;
@Inject
@Named("secondBaseObject")
private BaseClass secondBaseObject;

public void processSomething() {
// ... do something that requires both firstBaseObject and secondBaseObject to already be initialized on each call
}
}

关于java - 谷歌指南 : use injected factory to instantiate multiple objects in a class?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34279529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com