【发布时间】:2011-06-12 04:37:17
【问题描述】:
我的问题是,我如何将 guice 提供者的强大功能(他们限定实例范围的能力)用于数据对象?
原因如下:我有一个会话范围的类 WebPage,它根据来自数据库对象 DAO 的 Web 请求获取数据。
//Scope of WebPage: SESSION
class WebPage{
Provider<DAO> daoProvider; //Scope of DAO: REQUEST
WebPage(Provider<DAO> daoProvider){
this.daoProvider = daoProvider;
}
public String getMyString(){
return daoProvider.get().getMyString();
}
public int getMyInt(){
return daoProvider.get().getMyInt();
}
}
WebPage 对象是 Web 框架的一部分,它使所有页面对象保持在会话中。在每次请求时,getMyString 和 getMyInt 方法都会被调用多次以获取值,然后再将它们显示给页面上的用户。假设DAO 对象附加到表中的一个特定行,并且只从该行获取数据。
出于性能原因,我需要daoProvider 始终返回相同的实例,以避免每次调用getMyString 或getMyInt 时都重新连接到数据库。另一方面,必须跨请求更新实例,以便在页面刷新后对数据库的任何更新对用户可见。
所以我正在寻找的是在会话范围的WebPage 对象内的DAO 的请求范围的提供者。问题是我不明白如何在 Guice 中连接它。我试过了,但没有用:
class DAO{
Result row;
DAO(int rowId){
//opens DB connection and establishes a link
//to the object in question
this.row = attachRow(rowId);
}
String getMyString(){
this.row.getData("mystring");
}
int getMyInt(){
this.row.getIntData("myint");
}
}
interface DAOProviderFactory {
Provider<DAO> create(int rowId);
}
class DAOProviderFactoryImpl implements DAOProviderFactory {
@Override
public Provider<DAO> create(int rowId) {
return new DAOProviderImpl(rowId);
}
}
@RequestScoped
class DAOProviderImpl implements Provider<DAO> {
int rowId;
public DAOProviderImpl(int rowId) {
this.rowId = rowId;
}
@Override
public DAO get() {
//I want this instance to be request-scoped!
return new DAO(rowId);
}
}
//Then bind it in the module
bind(DAOProviderFactory.class).to(DAOProviderFactoryImpl.class);
这不起作用,因为调用 daoProvider.get() 会在每次调用时返回一个新实例(无作用域)。我想这是因为我的 DAOProviderImpl 对象不是由 Guice 实际管理的。另一个问题是相当数量的样板。
如何使用请求范围的提供程序为具有特定 rowId 的 DAO 实例提供服务?
如果有人能让我走上正确的道路,我会非常感激!提前致谢。
【问题讨论】: