我有以下代码,其中我不明白 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");
}
}
在这段代码中,没有任何地方创建了类 EmailService 的新实例,类似于 (new EmailService())。
慕慕森
相关分类