在spring上下文初始化之前运行代码

在tomcat 7上运行web-app,我的部署描述符包含2个侦听器,一个我创建的自定义侦听器,另一个是
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);
    }
}

使用这种方法无法解决问题,测试类和我的所有spring bean首先被初始化.

提前致谢

最佳答案 使用
@BeforeClass在测试类中注释静态方法并在那里进行初始化.例如:

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

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

如果您的初始化代码需要访问类字段,因此不能是静态的,那么您可以设置TestExecutionListener并实现beforeTestClass().有关示例,请参见this blog post.

点赞