Guice-绑定由辅助注射工厂创建的实例 [英] Guice - Binding an instance created by assisted injection factory

查看:52
本文介绍了Guice-绑定由辅助注射工厂创建的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一个类A,它的构造函数看起来像这样:

Let's say that there's class A that's constructor looks something like that:

public A(@Assited long id, @Assisten String name, ServiceA serviceA, ServiceB serviceB)

还有一个AFactory:

And there's AFactory:

public interface AFactory{

    A create(long id, String name);
}

因此,要创建A的实例,我显然需要执行以下操作:

So to create an instance of A I obviously need to do something like that:

injector = Guice.createInjector(new MyModule());
AFactory af = injector.getInstance(AFactory .class);
A a = AFactory.create(100, "mike");

但是,假设我还有其他类:例如,具有成员A类型的成员的B类,C类和D类(具有字段注入,但也可以是ctor):

BUT, Let's say I have other classes: Class B, Class C and Class D that has a member with type A, for example(with field injection but can be ctor also):

    public class B{
       @Inject
       A a;
    }

我希望将A的相同实例注入到这些类中.但仍然可以选择将A的另一个实例注入其他类(例如E和F类).

And I want that the same instance of A will be injected to those classes. But still have the option to inject another instance of A to other classes (let's say Class E and F).

这样做的正确方法是什么?我只是想不出一种干净的方法来做到这一点.

What is the correct way of doing that? I just can't think of a clean way to do that.

推荐答案

您可以构建模块以使用提供程序(我正在使用 @ Provides 方法,但您可以使用完整的提供程序类或实例(如果需要),并将一致的A标记为

You could structure your module to use Providers (I'm using @Provides methods below, but you can use full Provider classes or instances if you'd like), and mark the consistent A as @Singleton. If you want two bindings of A (consistent and inconsistent), at least one of them should be marked with a binding annotation; I'm using @Named here out of convenience, but you can use any binding annotation as listed in the docs.

public class AModule extends AbstractModule {
  @Override public void configure() {
    // Install your AFactory module. Here, injections for AFactory should succeed.
    install(new FactoryModuleBuilder().build(AFactory.class));
  }

  /**
   * Provides a singleton @Named("consistent") A.
   * Inject @Named("consistent") A into B, C, and D; Guice will cache the instance.
   */
  @Provides @Singleton @Named("consistent")
      A provideConsistentA(AFactory factory) {
    return factory.create(100, "mike");
  }

  /**
   * Provides an unscoped A.
   * Inject A without an annotation into E and F; each instance will be separate.
   */
  @Provides @Singleton A provideUnscopedA(AFactory factory) {
    return factory.create(200, "jeff");
  }
}

这篇关于Guice-绑定由辅助注射工厂创建的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆