假设我有一些消息类,如下所示。 (这是一个简单的组合类。)
Suppose I have some Message class like the following. (This is a made-up class for simplicity.)
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 code>的 send()方法。但是我该怎么做?
Since I have different MessageSender implementations, and might want to unit test this sending ability, I think I should be injecting the MessageSender in Message's send() method. But how do I do this?
我看到的所有的Guice示例,我理解似乎在构造函数中注入:
All the Guice examples I've seen and that I understand seem to do the injection in 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); } }但是我的 code>类在其构造函数中接收一个 text 参数,我不想注入。所以我应该做什么?
But my Message class takes in a text argument in its constructor, which I don't want to inject. So what am I supposed to do instead?
(注意:我是一个完整的Google Guice noob,我认为我了解依赖注入,但是我不明白您可以使用辅助注射来通过工厂提供文本以及消息。
(Note: I'm a complete Google Guice noob. I think I understand dependency injection, but I don't understand how to actually implement it with Guice.)
推荐答案发件人由Guice实例化:
You could use assisted injection to provide the text through a factory, along with the message sender instantiated by 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); }辅助注册维基
更多推荐
Guice只注入一些构造函数
发布评论