Constructor injection using Guice

I have sample code that uses factories. I would like to clear the code by deleting the factories and use Guice instead. I tried to do this, but I hit a small checkpoint. I am really new to Guice, so I hope someone can help me here.

Existing customer code (using factories):

public class MailClient { public static void main(String[] args) { MailConfig config = MailConfigFactory.get(); config.setHost("smtp.gmail.com"); Mail mail = MailFactory.get(config); mail.send(); } } 

My refactoring attempt using Guice:

 //Replaces existing factories public class MailModule extends AbstractModule { @Override protected void configure() { bind(Mail.class) .to(MailImpl.class); bind(MailConfig.class) .to(MailConfigImpl.class); } } public class MailImpl implements Mail { private final MailConfig config; @Inject public MailImpl(MailConfig config) { this.config = config; } public void send() { ... } } public class MailClient { public static void main(String[] args) { MailModule mailModule = new MailModule(); Injector injector = Guice.createInjector(mailModule); MailConfig config = injector.getInstance(MailConfig.class); config.setHost("smtp.gmail.com"); Mail mail = //?? mail.send(); } } 

How do I build an instance of MailImpl using the config object in my recycled MailClient? Should I use Guice this way?

+6
java dependency-injection guice
source share
3 answers

Take a look at AssistedInject . It seems that this problem has been resolved.

+3
source share

There are 2 possible solutions: 1) also binds the configuration as a guice object, including its host parameter. just enter Mail, in your main method you cna ignore the fact that mail has additional dependencies.

2) mail must be configured individually for each dispatch (recipient?). then you have no choice, but create it yourself using MailFactory.

+2
source share

You can do everything in MailModule as follows:

 public class MailModule extends AbstractModule { @Override protected void configure() { ... // other bindings } @Provides MailConfig getMailConfig( ... ) { MailConfig config = new MailConfig( ... ); config.setHost("smtp.gmail.com"); config; } } 

If you want a one-point MailConfig, add the @Singleton annotation to getMailConfig () and Bob to your uncle.

Note that getMailConfig arguments must be related. When you bind commonly used types such as String, be sure to add a binding annotation.

0
source share

All Articles