我有以下代码,在这些代码中,我不了解在何处创建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类的新实例。
答案 0 :(得分:3)
MyApplication
的构造函数,并发现它依赖于MessageService
(public MyApplication(MessageService service)
)。之所以采用此构造函数,是因为它用@Inject
AppInjector
中,您指定了MessageService
的实现为EmailService
(bind(MessageService.class).to(EmailService.class);
)EmailService
通过Java Reflection API实例化。通过Class.newInstance
EmailService
后,将其作为参数传递给MyApplication.class.newInstance()
工厂。注意:
EmailService
不具有依赖项的原因。EmailService
实例是单例的,因为它被标记为@Singleton
,因此,如果对它有更多依赖性,将注入完全相同的实例bind(MessageService.class).toInstance(new EmailService());