问题描述
我有一些使用工厂的示例代码。我想通过删除工厂来清理代码,而改用Guice。我尝试这样做,但遇到了一个小障碍。我对Guice真的很陌生,所以我希望有人能在这里为我提供帮助。
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();
}
}
我尝试使用Guice进行重构:
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();
}
}
如何构造<$ c $的实例c> MailImpl 在修订后的MailClient中使用对象 config
?我应该以这种方式使用Guice吗?
How would I construct an instance of MailImpl
using the object config
in my revised MailClient? Should I be using Guice in this way?
推荐答案
看看。看来可以解决这个问题。
Take a look at AssistedInject. It appears to address this problem.
这篇关于使用Guice进行构造函数注入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!