我有下面的代码,其中我不明白 EmailService 的新实例到底是在哪里创建的。我尝试查看许多其他 stackoverflow 对话,但仍然无法弄清楚。
public interface MessageService {
void sendMessage(String msg, String recipient);
}
@Singleton
public class EmailService implements MessageService {
@Override
public void sendMessage(String msg, String recipient) {
System.out.println("Sending Email to"+recipient+"Msg is:" + msg);
}
}
public class MyApplication {
private MessageService service;
@Inject
public MyApplication(MessageService service) {
this.service = service;
}
public void sendMessage(String msg, String recipient) {
this.service.sendMessage(msg, recipient);
}
}
public class AppInjector extends AbstractModule {
@Override
protected void configure() {
bind(MessageService.class).to(EmailService.class);
}
}
public class ClientApplication {
public static void main(String[] args) {
Injector inj = Guice.createInjector(new AppInjector());
MyApplication app = inj.getInstance(MyApplication.class);
app.sendMessage("How are you?", "hello@hello.com");
}
}
在此代码中,没有创建类似 (new EmailService()) 的类 EmailService 的新实例。
最佳答案
- 通过反射,Guice 分析
MyApplication
的构造函数,发现它依赖于MessageService
(public MyApplication(MessageService service)
)。正是这个构造函数被采用,因为它被标记为@Inject
- Guice 尝试找出该接口(interface)的绑定(bind)。在
AppInjector
中,您指定MessageService
的实现是EmailService
(bind(MessageService.class).to(EmailService.class);
) EmailService
通过 Java Reflection API 实例化。这是通过Class.newInstance
完成的- 创建
EmailService
后,它会作为参数传递给MyApplication.class.newInstance()
工厂。
注释:
- 默认情况下,如果您没有指定任何其他构造函数,则会有一个不带参数的默认构造函数,这就是
EmailService
没有依赖项的原因。 EmailService
实例是单例,因为它被标记为@Singleton
,因此如果对它有更多依赖,将会注入(inject)完全相同的实例- 如果您想创建binding to instance ,您可以使用以下代码:
bind(MessageService.class).toInstance(new EmailService());
- Google 图书馆的文档总是很丰富。我建议您阅读此维基:google/guice/wiki
关于java - Google Guice 依赖注入(inject) - 对象到底是在哪里创建的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649454/