Google Guice:使用注入工厂来实例化类中的多个对象?

时间:2015-12-15 01:24:20

标签: java dependency-injection guice

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
    }
}

我是否可以在firstBaseObject的每次通话中同时访问secondBaseObjectprocessSomething()processSomething()的每次调用都取决于已经实例化的这两个对象,它们是具有大量元数据的大对象。即,当这两行被击中时,我能否以某种方式确保factoryClass已被实例化?:

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

我在这两行上获得了NullPointerExceptions,因为factoryClass为空。

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

1 个答案:

答案 0 :(得分:2)

使用以下代码

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
    }
}

您不能使用字段或方法注入,因为在填充firstBaseObject和secondBaseObject之后,在factoryClass中注入。

OR

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
    }
}