2014-10-01 64 views
1

嗨我需要在我的應用程序啓動時發送電子郵件,並在我的應用程序停止時發送電子郵件。如何檢查彈簧框架的啓動和停止?

使用Spring ...

public class Main { 
    public static void main(String[] args) { 
     FileSystemXmlApplicationContext fac = new FileSystemXmlApplicationContext("config/applicationContext.xml"); 
    } 
} 

其餘的是通過應用程序上下文有線起來......

我想我可以只注入一個簡單的bean實現智能的生命週期和發送電子郵件從start()stop()方法?

回答

2

您可以簡單地使用默認單身範圍的bean,並宣佈它的init和destroy方法。這個bean不需要遵守春天,可能是這樣的:

public class StartAndStop { 

    public void onStart() { 
     // send the mail signaling start of application 
     ... 
    } 

    public void onStop() { 
     // send the mail signaling stop of application 
     ... 
    } 
} 

在xml配置:

<bean class="org.example.StartAndStop" init-method="onStart" destroy-method="onStop"/> 

而且隨着Java配置當然

@Configuration 
public class Configurer { 

    @Bean(initMethod="onStart", destroyMethod="onStop") 
    StartAndStop startAndStop() { 
     return new StartAndStop(); 
    } 
    ... other beans configuration ... 
} 

,你也可以使用Spring在豆上設置屬性...

+0

我覺得我更喜歡這個... – user432024 2014-10-01 20:59:12

+0

兩個同樣好的答案,但在我的情況下,我選擇了這種方法,並將其標記爲接受的答案。 :) – user432024 2014-10-02 13:12:04

+0

同樣值得一提的是,這個工作正確,你還需要registerShutdownHook()。 – user432024 2014-10-02 14:23:31

1

Spring在這些場景中自動引發事件。

@Component 
public class ContextRefreshListener implements ApplicationListener<ContextRefreshedEvent> { 

    @Override 
    public void onApplicationEvent(final ContextRefreshedEvent event) { 
    // is called whenever the application context is initialized or refreshed 
    } 
} 

春提出了以下應用程序上下文事件:

您可以通過創建一個ApplicationListener豆監聽事件

Standard and Custom Events documentation

+0

好吧我試着讓你知道。謝謝 – user432024 2014-10-01 20:15:52

+0

我需要明確地打電話嗎?新的ClassPathXmlApplicationContext(「applicationContext.xml」); \t \t cac.start(); – user432024 2014-10-01 20:41:18

+1

看來我需要明確地調用start()和stop()。只有刷新事件會自動發佈。 – user432024 2014-10-01 20:50:41