2014-01-08 18 views
1

當應用程序啓動和停止時,我必須更新一個表條目。 我有一個服務,它具有對DAO方法的調用,但是當調用此DAO方法時,自動裝配的SessionFactory爲空。Spring:在啓動和停止Web應用程序時更新DB-table條目

我已經使用2種方法:

  1. @PostConstruct,@PreDestroy
  2. ApplicationListener onApplicationEvent()

在這兩種情況下我得到了SessionFactory在DAO類爲空。我在DAO類中使用Setter-Injection來注入SessionFactory

環境:JDBC-數據源,Hibernate的3.4,春季3.1.2的Weblogic 10.3

這將是巨大的,如果你能在正確的方向指向我。

更新: 感謝您的所有意見我解決了問題。我們的應用程序是EAR,我的DAO bean配置位於不同的WAR的applicationContext.xml中。我將DAO bean配置移動到了我的共享配置(appConfig.xml),它的工作方式就像魅力一樣。我使用@PostConstruct和@PreDestroy

+1

向我們展示您的上下文並向我們展示所涉及的類(即帶有「Session」的類工廠'注入)。 –

+1

您可能想查看['SmartLifeCycle'](http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/SmartLifecycle.html) – 2014-01-08 18:52:07

+0

將代碼發佈到您所在的位置注入會話工廠併發布spring配置的xml文件。 –

回答

0

如果你想在上下文初始化後執行方法,你必須使用ContextRefreshedEvent。在上下文銷燬的情況下,您應該使用ContextStoppedEvent,但您也必須重新考慮,並不保證此事件將被公佈。

@Component 
public class SpringStartedListener implements ApplicationListener<ContextRefreshedEvent> { 

    @Override 
    public void onApplicationEvent(ContextRefreshedEvent event) { 
    // do something 
    } 
} 

@Component 
public class SpringClosedListener implements ApplicationListener<ContextStoppedEvent> { 

    @Override 
    public void onApplicationEvent(ContextStoppedEvent event) { 
    // do something 
    } 
} 

如果您需要更多的詳細信息,請參閱http://www.tutorialspoint.com/spring/event_handling_in_spring.htm

1

您可以使用它SmartLifecycle接口,然後將其配置爲一個bean做:

<bean class="com.my.package.MySmartlifecycle"> 

以及實現:

public class MySmartLifecycle implements SmartLifecycle{ 
    //autowire anything you need from context 
    @Override 
    public void start() { 
     //do stuff on startup here 
    } 

    @Override 
    public void stop() { 
     //do stuff on shutdown here 
    } 

    @Override 
    public boolean isRunning() { 
     return false; 
    } 

    @Override 
    public int getPhase() { 
     return 0; 
    } 

    @Override 
    public boolean isAutoStartup() { 
     return true; 
    } 

    @Override 
    public void stop(Runnable callback) { 

    } 

} 
+0

有趣的好知道它謝謝。 – John

相關問題