您可以实现一个@ApplicationScoped
缓存 DB 值的托管 bean。只需通过它访问数据,而不是直接使用视图 bean 中的 DAO:
@ManagedBean
@ApplicationScoped
public class CacheManager(){
private static Date lastChapterAccess;
private static Date lastCategoryAccess;
private List<Chapter> cachedChapters;
private List<Category> cachedCategories;
private Dao dao;
//Refresh the list if the last DB access happened
//to occur more than one hour before
public List<Chapter> loadChapterStructure(){
if (lastChapterAccess==null || new Date().getTime()
- lastChapterAccess.getTime() > 3600000){
cachedChapters = dao.loadChapterStructure();
lastChapterAccess = new Date();
}
return cachedChapters;
}
public List<Category> loadCategoryStructure(){
if (lastCategoryAccess==null || new Date().getTime()
- lastCategoryAccess.getTime() > 3600000){
cachedCategories = dao.loadCategoryStructure();
lastCategoryAccess = new Date();
}
return cachedCategories;
}
}
@ManagedProperty
然后使用注释在任何你想要的地方注入 bean :
@ManagedBean
@ViewScoped
public class ViewBean{
@ManagedProperty(value="#{cacheManager}")
private CacheManager cacheManager;
//preRenderView Method
public void init(){
chapters = cacheManager.loadChapterStructure();
categories = cacheManager.loadCategoryStructure();
}
}