简体   繁体   English

Guice:通过方法创建对象

[英]Guice: Creating objects by methods

Suppose I have two similar (but different) methods (or maybe static methods) create_x() and create_y() to create objects (call them x and y ) both (of class derived) of class Parser . 假设我有两个相似(但不同)的方法(或可能是静态方法) create_x()create_y()来创建对象(分别是派生类) Parser类的对象(分别称为xy )。

Now I want to bind the objects created by these two methods like as in answer to my previous question : 现在,我想绑定由这两种方法创建的对象,就像回答我的上一个问题一样

bind(Parser.class)
        .annotatedWith(Names.named("x"))
        .to(ParserXImplementation.class);

bind(Parser.class)
        .annotatedWith(Names.named("y"))
        .to(ParserYImplementation.class);

but with object created by create_x() , create_y() instead of instances of classes ParserXImplementation , ParserYImplementation . 但是使用由create_x()create_y()创建的对象,而不是ParserXImplementation类, ParserYImplementation类的实例。 (So that there is no necessity to create classes ParserXImplementation , ParserYImplementation .) (因此,不必创建类ParserXImplementationParserYImplementation 。)

Note that I want the objects to be singletons. 请注意,我希望对象是单例。

I want the answers both for the case if create_x() , create_y() are static methods and for the case if they are instance methods. 如果create_x()create_y()是静态方法,并且它们是实例方法,我都希望得到答案。 If they are instance methods, the class containing them may itself be subject to dependency injection. 如果它们是实例方法,则包含它们的类本身可能会进行依赖注入。

How to do this? 这个怎么做? (injecting dependencies to instances created by methods) (将依赖项注入由方法创建的实例)

From https://github.com/google/guice/wiki/ProvidesMethods : https://github.com/google/guice/wiki/ProvidesMethods

When you need code to create an object, use an @Provides method. 需要代码创建对象时,请使用@Provides方法。 The method must be defined within a module, and it must have an @Provides annotation. 该方法必须在模块中定义,并且必须具有@Provides批注。 The method's return type is the bound type. 该方法的返回类型是绑定类型。 Whenever the injector needs an instance of that type, it will invoke the method. 只要注入器需要该类型的实例,它将调用该方法。

public class BillingModule extends AbstractModule {
  @Override
  protected void configure() {
    ...
  }

  @Provides
  TransactionLog provideTransactionLog() {
    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
    transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
    transactionLog.setThreadPoolSize(30);
    return transactionLog;
  }
}

Further, it says that it can use annotation like @Named("x") and @Named("y") to differentiate x and y as described in the answer to Binding the same interface twice (Guice) . 此外,它说它可以使用@Named("x")@Named("y")类的注释来区分xy ,如对两次绑定同一接口(Guice)的回答中所述

This is what I need (however the method is defined inside a module rather than in an arbitrary class). 这就是我所需要的(但是方法是在模块内部而不是在任意类中定义的)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM