[英]How to tie the Lifecycle for a Spring Bean to the webapps' lifecycle?
我想創建一個具有start()
和stop()
方法的bean。 當webapp的上下文處於活動狀態時,在Spring的運行時啟動期間會調用start()
。 取消部署或停止webapp時,將調用stop()
方法。
這是正確的:我用@PostConstruct
注釋我的start()
方法,用@PreDestroy
注釋stop()
方法?
通常在servlet世界中,我編寫了一個ServletContextListener。 我能從ServletContextListener訪問ApplicationContext嗎?
在bean中實現Lifecycle或SmartLifecycle接口,如中所述
public interface Lifecycle {
void start();
void stop();
boolean isRunning();
}
然后,您的ApplicationContext將其啟動和停止事件級聯到所有生命周期實現。 另請參見JavaDocs:
您可以在描述時注釋start()
和stop()
方法,也可以告訴Spring顯式調用它們,例如
<bean class="MyClass" init-method="start" destroy-method="stop"/>
至於ServletContextListener
,它不會輕易訪問Spring上下文。 最好使用Spring自己的生命周期來進行bean初始化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.