2012-07-22 135 views
4

不是Tomcat 7上運行的Web應用程序內運行之前的代碼,我的部署描述符包含2個監聽器,自定義的其中一個我創建和Spring的另一個問題:Spring上下文初始化

<listener> 
    <listener-class>com.company.appName.web.context.MyContextListener</listener-class> 
</listener> 

<!-- Creates the Spring Container shared by all Servlets and Filters --> 
<listener> 
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 
</listener> 

正如我跑我的集成測試,我的偵聽器根本不會被調用,所以爲了克服它,我正在對自己進行一些初始化(調用一些靜態方法,基本上是從我的這個偵聽器調用的)。無論如何,我認爲我在這裏錯過了一些東西,聽衆什麼時候被叫到?爲什麼在我的集成測試中不會初始化?更具體地講,Spring上下文被弄初始化那是因爲我聲明瞭它在我的測試類的頂部:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "classpath:testApplicationContext.xml" }) 

所以從來沒有實際使用的web.xml中..

在這種情況下, ,Spring的上下文總是被首先調用,在它被初始化之前我沒有做任何事情的機會 - 是這樣嗎?有沒有辦法在spring的上下文之前運行一些代碼?

更新: 我也想提一提,我使用的是@BeforeClass標註在我的測試套件:

@RunWith(Categories.class) 
@IncludeCategory(HttpTest.class) 
@SuiteClasses({ <MY TEST CLASSES> }) 
public class HttpSuiteITCase { 

    /** 
    * Run once before any of the test methods. 
    */ 
    @BeforeClass 
    public static void setTestsConfigurations() { 
    TestConfiguration.setup(false); 
    } 
} 

使用這種方法不能解決問題,測試類,以及我所有的春豆首先得到初始化。

在此先感謝

回答

2

標註一個static方法在測試類@BeforeClass,做你的初始化那裏。例如:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration({ "classpath:testApplicationContext.xml" }) 
public class TestTest { 

    @BeforeClass 
    static public void beforeClass() { 
     // do intialization here 
    } 

如果你的初始化代碼需要訪問類的字段,因此不能爲static則相反,你可以建立一個TestExecutionListener和實施beforeTestClass()。以this blog post爲例。

+0

我曾嘗試它,昨天並沒有出於某種原因(我想從我的套件,因此運行的@BeforeClass方法將只運行一次。今天的作品..我昨天太困了:) – forhas 2012-07-23 07:20:46

0

在測試上下文中,您可以通過在bean中使用init-method來完成。

<bean id="exampleInitBean" class="examples.ExampleBean" init-method="init"/> 

公共類叫exampleBean {

public void init() { 
    // do some initialization work 
} 

}

+0

好吧,有趣。但是誰能確保這個bean在我的所有春豆中首先被初始化? – forhas 2012-07-23 05:03:17

+0

因爲你必須通過春季和春季豆生命週期的初始化回調。 http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html。 爲了保證您可以自己嘗試一下。 – dhamibirendra 2012-07-23 05:08:19

相關問題