Sa'*_*'ad 1 dependency-injection guice
检查Guice,我喜欢它.我目前有问题,guice通过注入我需要的所有必需依赖项来解决它.但我想知道我是否以错误的方式使用Guice.我需要的是根据特定实例定义绑定.为了实现这一点,我在模块中传递了实例.
例如,考虑以下内容(有点类似于我的问题):
public class CustomerModule extends AbstractModule {
private Customer customer;
public CustomerModule(Customer customer){
this.customer = customer;
}
@Override
public void configure() {
bind(ReportGenerator.class).to(HtmlReportGenerator.class);
}
@Provides
Account providePurchasingAccount() {
return customer.getPurchasingAccount();
}
}
Run Code Online (Sandbox Code Playgroud)
我使用此模块将Account依赖项注入到需要特定客户帐户的报表生成器类中.例如,用户选择特定客户并说,想要显示生成的报告.我有方法
public void printReport (Customer customer){
Injector injector = Guice.createInjector(new CustomerModule(customer));
ReportGenerator reportGenerator = injector.getInstance(ReportGenerator.class);
showReport(reportGenerator.generate())
}
Run Code Online (Sandbox Code Playgroud)
工作完成后,我完成了这个模块.
这是一个好用的guice吗?
接受Module的构造函数参数是适当且有用的.在为类似对象进行绑定时,这是一种特别常见的模式.例:
// Installs @Named("accounts") Db to the given impl, backed with the given cache.
install(new DbModule("accounts", AccountDb.class, InMemoryCache.class));
// Same as above.
install(new DbModule("users", UserDb.class, DiskCache.class));
install(new DbModule("products", ProductDb.class, CustomProductCache.class));
Run Code Online (Sandbox Code Playgroud)
也就是说,每个动作(例如printReport)创建一个新的根注入器并不常见.由于Guice反射性地查询类及其依赖项,因此注入器创建可能需要很长时间.相反,在应用程序启动时创建根注入器更为常见,然后在需要以您拥有它们的方式绑定特定对象时创建子注入器.
虽然你可能有意义地为每个动作临时创建一个全新的根注入器,你拥有它的方式,但请记住,未来的开发可能会使单一操作或应用程序级范围超出单个操作或您的对象图形可能会增长,使得动作中的根注入器创建不再具有足够的性能供您使用.如果/何时发生这种情况,您可能希望将大多数Injector创建和配置转移到可预测的启动流程,并且只将您的Customer(以及其他任何内容)绑定到子注入器中.
| 归档时间: |
|
| 查看次数: |
835 次 |
| 最近记录: |