2011-12-20 102 views
1

我想在一個spring singleton bean中啓動和停止一個石英調度器。但postconstruct被調用了兩次,而predestroy並沒有被調用。 This鏈接說因爲代理它自然被稱爲兩次,但這是造成postconstruct方法中的異常。我只想在加載單例bean之後調用postConstruct一次。Spring @PreDestroy和@PostConstruct註釋

回答

0

我編寫了contextloader偵聽器並更改了web.xml偵聽器,所以我只能初始化bean一次。

<listener> 
     <listener-class> 
       CustomContextLoaderListener 
     </listener-class> 
    </listener> 

public class CustomContextLoaderListener extends 
         org.springframework.web.context.ContextLoaderListener{ 
    Scheduler scheduler; 

    @Override 
    public void contextInitialized(javax.servlet.ServletContextEvent event) { 
      try{ 
      super.contextInitialized(event); 
      this.scheduler= WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()).getBean(Scheduler.class); 

    } 

    @Override 
    public void contextDestroyed(ServletContextEvent event){ 

      super.contextDestroyed(event); 
      scheduler.stopSchedulers(); 


    } 
0

你爲什麼不嘗試使用init-method或嘗試實現初始化bean。這些提供了postConstruct的替代方法。

當彈簧豆被卸載時,即當容器關閉或者通過其他方式調用ConfigurableApplicationContext方法中的close()方法時,調用preDestroy。

+0

init-metod也調用了兩次 – ayengin 2011-12-26 19:21:51