Guice只注入一些构造函数

时间:2012-02-06 00:29:41

标签: java dependency-injection guice

假设我有一些Message类,如下所示。 (为简单起见,这是一个简化的课程。)

public class Message {
  private String text;

  public Message(String text) {
    this.text = text;
  }

  public void send(Person recipient) {
    // I think I should be Guice-injecting the sender.
    MessageSender sender = new EmailBasedMessageSender();
    sender.send(recipient, this.text);
  }
}

由于我有不同的MessageSender实现,并且可能想要对此发送功能进行单元测试,我想我应该在MessageSender的{​​{1}}方法中注入Message 。但是我该怎么做呢?

我见过的所有Guice示例和我理解的似乎都在构造函数中执行注入:

send()

但我的public class Message { private String text; private MessageSender sender; // ??? I don't know what to do here, since the `text` argument shouldn't be injected. @Inject public Message(String text, MessageSender sender) { this.text = text; this.sender = sender; } public void send(Person recipient) { this.sender.send(recipient, this.text); } } public class MessageSenderModule extends AbstractModule { @Override protected void configure() { bind(MessageSender.class).to(EmailBasedMessageSender.class); } } 类在其构造函数中引入了Message参数,我不想注入它。那么我应该做什么呢?

(注意:我是一个完整的Google Guice noob。我想我理解依赖注入,但我不明白如何用Guice实现它。)

1 个答案:

答案 0 :(得分:19)

您可以使用辅助注入通过工厂提供文本,以及由Guice实例化的邮件发件人:

public class Message {
  private String text;
  private MessageSender sender;

  @Inject
  public Message(@Assisted String text, MessageSender sender) {
    this.text = text;
    this.sender = sender;
  }

  public void send(Person recipient) {
    this.sender.send(recipient, this.text);
  }
}

厂:

public interface MessageFactory{
    Message buildMessage(String text);
}

模块:

public class MessageSenderModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(MessageSender.class).to(EmailBasedMessageSender.class);
    FactoryModuleBuilder factoryModuleBuilder = new FactoryModuleBuilder();
    install(factoryModuleBuilder.build(MessageFactory.class));
  }
}

用法:

@Inject MessageFactory messageFactory;

void test(Recipient recipient){
  Message message = messageFactory.buildMessage("hey there");
  message.send(recipient);
}

Assisted Injection Wiki