2012-02-07 58 views
2

我知道這個問題是Execute method on startup in spring的重複。然而,我已經嘗試了針對該問題接受的答案中發佈的建議,並沒有爲我工作。因此,我懷疑,儘管這裏詢問的問題是相同的,但我強烈地認爲根本原因是不同的,因此需要不同的答案/解決方案。春天如何執行方法

我想讓Spring在啓動時創建一個bean,並立即執行它的一個方法。

我的Spring配置(heartbeat-config.xml):

<beans (all the xmlns stuff here ommitted for brevity)> 
    <bean id="heartbeat" class="org.me.heartbeat.Heartbeat"/> 
</beans> 

而且Heartbeat.java

public class Heartbeat 
{ 
    @PostConstruct 
    public void start() 
    { 
     System.out.println("I should see this message in the logs somewhere!!"); 
    } 
} 

最後,我web.xml

<?xml version="1.0" encoding="UTF-8"?> 
<web-app 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    version="2.4"> 

    <!-- The display name of this web application --> 
    <display-name>Heartbeat</display-name> 

    <context-param> 
     <param-name>contextConfigLocation</param-name> 
     <param-value>/WEB-INF/heartbeat-config.xml</param-value> 
    </context-param> 

    <listener> 
     <listener-class> 
      org.springframework.web.context.ContextLoaderListener 
     </listener-class> 
    </listener> 
</web-app> 

當我在Tomcat的我不運行這個」沒有任何啓動錯誤。 Tomcat看起來像運行健康(我可以從日誌中看出)。然而,我沒有看到在我的start()方法(Tomcat將所有標準輸出重定向到其日誌文件)中應該由System.out調用生成的日誌中的任何輸出。

我可以在這裏看到什麼嗎?有沒有明顯的診斷,我可以執行?

+0

你需要告訴我們當你試着從另一個問題的解決方案時發生了什麼,否則我們不知道如何回答不同,這仍然是重複的。 – skaffman 2012-02-07 20:32:57

+0

或者你不能從構造函數執行此操作? – flurdy 2012-02-07 20:37:54

+0

呵呵,我從另外一個問題中唯一的改變是添加'@ PostConstruct'註解。無論哪種方式都有相同的結果,因此該解決方案對我無效,而對另一個提問者卻有效。 – IAmYourFaja 2012-02-07 20:39:45

回答

3

最簡單的方法就是忘掉註釋和你的bean定義更改爲:

<bean id="heartbeat" class="org.me.heartbeat.Heartbeat" init-method="start"/> 

如果你想註釋需要聲明的context命名空間,並把這個詮釋你的applicationContext.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation=" 
     http://www.springframework.org/schema/beans 
     http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context 
     http://www.springframework.org/schema/context/spring-context-2.5.xsd"> 

    <!-- Enable @PostConstruct, @PreDestroy and friends in Spring --> 
    <context:annotation-config/> 

    <bean id="heartbeat" class="org.me.heartbeat.Heartbeat"/> 
</beans> 

注意:檢查命名空間,它們是從網上copypasted。