I have some sample code which is using factories. I'd like to clean up the code by removing the factories and use Guice instead. I attempted to do this but I hit a small roadblock. I am really new to Guice, so I am hoping someone can help me out here.
Existing client 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 attempt to refactor 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 would I construct an instance of MailImpl
using the object config
in my revised MailClient? Should I be using Guice in this way?