Java – Guice only registers some constructors

Suppose I have some message classes, as shown below This is a simple combination class

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

Since I have different messagesender implementations and may want to unit test this sending capability, I think I should inject messagesender into the send () method of message But what should I do?

All the Guice examples I saw, I understand, seem to be injected into the constructor:

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

But my message class accepts a text parameter in its constructor, and I don't want to inject it What should I do?

(Note: I am a complete Google Guice noob. I think I understand dependency injection, but I don't understand how to actually implement it with Guice.)

Solution

You can use assisted injection to provide text through the factory and message senders instantiated by Guice:

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

  @Inject
  public Message(@Assisted String text,this.text);
  }
}

Factory:

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

modular:

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

Usage:

@Inject MessageFactory messageFactory;

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

Assisted Injection Wiki

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>