從Java EE 5規範開始,Servlet中增加了兩個影響Servlet生命週期的註解(Annotion);@PostConstruct和@PreDestroy。這兩個註解被用來修飾一個非靜態的void()方法 。寫法有如下兩種方式:
@PostConstruct
Public void someMethod() {}
或者
public @PostConstruct void someMethod(){}
被@PostConstruct修飾的方法會在服務器加載Servle的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之後執行,init()方法之前執行。PreDestroy()方法在destroy()方法執行執行之後執行
被註解的Servlet生命週期
需要注意的是,註解會多多少少地影響到服務器的啓動速度。服務器在啓動時候會遍歷Web 應用的WEB-INF/classes下的所有class文件與WEB-INF/lib下的所有jar文件,以檢查哪些類使用了註解。如果應用程序中沒有 使用任何註解,可以在Web.xml中設置的metadata-complete屬性爲true.(支持@PostConstruct和 @PreDestroy的服務器需要支持Servlet2.5規範。Tomcat5.x僅支持Servlet2.4規範。)
我現在要說的是用實例說明它有什麼作用。
比如說我有一種情況,在我的servlet初始化加載之前我想處理一些東西,像加載緩存等等。
怎麼做。@PostConstruct就派上用場了。那爲什麼這玩意用的不多呢,這是因爲如果初始化之前我們要加載或處理某些玩意完全可以在構造器初始化時就處理了,但這種方法需要自己重寫構造器。好吧。直接上代碼看看具體用它的時候怎麼做的。
-
package com.whaty.products.whatysns.web.info;
-
-
import javax.annotation.PostConstruct;
-
import javax.annotation.Resource;
-
-
import org.springframework.stereotype.Service;
-
import org.springframework.util.Assert;
-
-
import com.whaty.framework.cache.core.model.Cache;
-
import com.whaty.framework.cache.core.service.CacheService;
-
import com.whaty.framework.cache.entitycache.service.EntityCacheHelper;
-
import com.whaty.framework.cache.entitycache.service.IEntityDaoAdapter;
-
-
-
-
-
-
-
@Service("AjaxCacheableService")
-
public class AjaxCacheableService{
-
-
@Resource(name="cacheService")
-
protected CacheService cacheService;
-
-
protected boolean useReadWriteEntityDao = false;
-
protected boolean useCache = true;
-
protected int entityCacheMaxSize = 1000;
-
protected int entityCacheMaxLiveSeconds = 3600;
-
protected Cache entityCache;
-
-
-
-
-
-
@PostConstruct
-
public void init() {
-
Assert.notNull(cacheService, "cacheService must be set!");
-
getCache();
-
}
-
-
-
-
-
-
protected Cache getCache() {
-
if (entityCache == null) {
-
entityCache = cacheService.addCache(this.getClass().getName(),entityCacheMaxLiveSeconds);
-
}
-
return entityCache;
-
}
-
-
-
-
-
-
-
public Object getCache(String id) {
-
String strid = String.valueOf(id);
-
Object o = entityCache.get(strid);
-
return o;
-
}
-
-
public Object putCache(int tTLSeconds,String cacheId,Object value) {
-
String strid = String.valueOf(cacheId);
-
Object o = entityCache.get(strid);
-
if (o != null) {
-
return o;
-
} else {
-
entityCache.put(strid, value, tTLSeconds);
-
return value;
-
}
-
}
-
-
}