gpt4 book ai didi

java - Guice 只注入(inject)一些构造函数

转载 作者:搜寻专家 更新时间:2023-10-30 21:04:27 26 4
gpt4 key购买 nike

假设我有一些 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 实现,并且可能想对这种发送能力进行单元测试,我认为我应该在 Message 中注入(inject) MessageSender > 的 send() 方法。但我该怎么做呢?

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

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 类在其构造函数中接受了一个 text 参数,我不想注入(inject)它。那么我应该怎么做呢?

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

最佳答案

您可以使用辅助注入(inject)通过工厂提供文本,以及由 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

关于java - Guice 只注入(inject)一些构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9154410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com