@postconstruct初始化的操作
從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就派上用場了。那為什麼這玩意用的不多呢,這是因為如果初始化之前我們要載入或處理某些玩意完全可以在構造器初始化時就處理了,但這種方法需要自己重寫構造器。好吧。直接上程式碼看看具體用它的時候怎麼做的。
1 ackage com.whaty.products.whatysns.web.info; 2 3 import javax.annotation.PostConstruct; 4 import javax.annotation.Resource; 5 6 import org.springframework.stereotype.Service; 7 import org.springframework.util.Assert; 8 9 import com.whaty.framework.cache.core.model.Cache; 10 import com.whaty.framework.cache.core.service.CacheService; 11 import com.whaty.framework.cache.entitycache.service.EntityCacheHelper; 12 import com.whaty.framework.cache.entitycache.service.IEntityDaoAdapter; 13 14 /** 15 * @author bc_qi 16 * @param <KEY> 17 * @param <ENTITY> 18 */ 19 @Service("AjaxCacheableService") 20 public class AjaxCacheableService{ 21 22 @Resource(name="cacheService") 23 protected CacheService cacheService; 24 25 protected boolean useReadWriteEntityDao = false; 26 protected boolean useCache = true; 27 protected int entityCacheMaxSize = 1000; 28 protected int entityCacheMaxLiveSeconds = 3600; 29 protected Cache entityCache; 30 31 32 /** 33 * 構造方法執行後,初始化, 34 */ 35 @PostConstruct 36 public void init() { 37 Assert.notNull(cacheService, "cacheService must be set!"); 38 getCache(); 39 } 40 41 /** 42 * 獲取cache 43 * @return 44 */ 45 protected Cache getCache() { 46 if (entityCache == null) { 47 entityCache = cacheService.addCache(this.getClass().getName(),entityCacheMaxLiveSeconds); 48 } 49 return entityCache; 50 } 51 52 /** 53 * @param id 54 * @param useCache 是否使用Cache 55 * @return 56 */ 57 public Object getCache(String id) { 58 String strid = String.valueOf(id); 59 Object o = entityCache.get(strid); 60 return o; 61 } 62 63 public Object putCache(int tTLSeconds,String cacheId,Object value) { 64 String strid = String.valueOf(cacheId); 65 Object o = entityCache.get(strid); 66 if (o != null) { 67 return o; 68 } else { 69 entityCache.put(strid, value, tTLSeconds); 70 return value; 71 } 72 } 73 74 }