@PostConstruct和@PostConstruct 注解 及ehcache 缓存 执行过程 小记
@PostConstruct 和@PostConstruct 注解
从Java EE 5规范开始,Servlet中增加了两个影响Servlet生命周期的注解(Annotion);@PostConstruct和@PreDestroy。这两个注解被用来修饰一个非静态的void()方法 。写法有如下两种方式:
@PostConstruct
Public void someMethod() {}
或者
public @PostConstruct void someMethod(){}
被@PostConstruct修饰的方法会在服务器加载Servle的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法执行执行之后执行。
ehcache 缓存 执行过程
加载servlet时,
通过initCache方法读取缓存配置文件来构建缓存实例
@PostConstruct void initCache() { logger = Logger.getLogger(getClass()); if (getCache() == null) { String clsName = getClass().getSimpleName(); URL url = getClass().getResource( SystemGlobals.getValue('/xx/ehcache.xml')); CacheManager manager = CacheManager.create(url); Cache c = manager.getCache(clsName); setCache(c); } if (logger.isDebugEnabled()) { logger.debug("初始化:" + getCache()); } }
构建实例后,需一次性加载缓存数据
@PostConstruct void init() { if (!isInitCategory) { initCategories(); isInitCategory = true; } if (!isInitBrand) { initBrands(); isInitBrand = true; } } private void initCategories() { Range<Category> range = categoryDao.select(); categoryCache.putAll(range.getData()); }
public void putAll(Collection<Category> categories) {
List<Category> list = new ArrayList<Category>(categories);
Element element = new Element(FQN_ALL, list);
cache.removeAll();
cache.put(element);
}
项目启动后,访问项目,读取缓存数据
private static Cache cache; private static final String FQN_ALL = "all"; private static final String FQN_KEY = "key"; private static final String FQN_CHILDREN = "children"; private static final String FQN_ROOT = "root"; @SuppressWarnings("unchecked") public Collection<Category> root() { String key = FQN_ROOT; Element element = cache.get(key); if (element != null) { return (List<Category>) element.getValue(); } List<Category> root = new ArrayList<Category>(); List<Category> categories = getCategories(); for (Category category : categories) { if (category.isRoot()) { root.add(category); } } element = new Element(key, root); cache.put(element); return root; } @SuppressWarnings("unchecked") private List<Category> getCategories() { Element element = cache.get(FQN_ALL); if (element != null) { return (List<Category>) element.getValue(); } return new ArrayList<Category>(0); }