I have the below code in which i dont understand where exactly the new instance of EmailService is created. I tried to check many other stackoverflow conversations, but still couldnt get it clearly.
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");
}
}
nowhere in this code, new instance of class EmailService is created something like (new EmailService()).
MyApplication
's constructor and finds out that it depends on MessageService
(public MyApplication(MessageService service)
). Exactly this constructor is taken because it is marked with @Inject
AppInjector
you specified that implementation for MessageService
is EmailService
(bind(MessageService.class).to(EmailService.class);
)EmailService
is instantiated via Java Reflection API. It is done via Class.newInstance
EmailService
is created, it is passed as a parameter to MyApplication.class.newInstance()
factory.Notes:
EmailService
has not dependencies.EmailService
instance is a singleton because it is marked with @Singleton
, so if there will be more dependencies on it, exactly the same instance will be injectedbind(MessageService.class).toInstance(new EmailService());