Java SpringJUnit4ClassRunner是否为每个测试初始化bean?

Java SpringJUnit4ClassRunner是否为每个测试初始化bean?,java,spring,junit4,spring-test,Java,Spring,Junit4,Spring Test,下面的测试说明这个测试bean由Spring初始化了两次。我希望有人能告诉我为什么会这样,因为它应该只有一次。以下是测试: import org.apache.log4j.Logger; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.InitializingBean; import org.springframework.test.context.C

下面的测试说明这个测试bean由Spring初始化了两次。我希望有人能告诉我为什么会这样,因为它应该只有一次。以下是测试:

import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {} )
public class TestAfterPropsSet implements InitializingBean {

private static final Logger logger = Logger.getLogger(TestAfterPropsSet.class);

@Test
public void test1() {
    logger.debug("Test1");
}

@Test
public void test2() {
    logger.debug("Test2");      
}

public void afterPropertiesSet() throws Exception {
    logger.debug("Bean Initialized");       
}
} // end class
下面是bean文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    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">
</beans>

这不是春季大会。您应该遵循JUnit约定,即套件范围内的初始化或解构应该相应地在@BeforeClass和@AfterClass中完成,或者您可以使用@Autowire并让Spring处理对象的范围

将为每个测试构建一个新套件。这在JUnit3中更为明显,在JUnit3中,您必须使用指定的测试名称创建一个新套件

请看一下:

测试注释告诉JUnit 它所使用的公共作废方法 附件可以作为测试用例运行到 先运行JUnit构造的方法 然后是该类的新实例 调用带注释的方法。Any 测试引发的异常将被删除 JUnit报告为失败。如果没有 异常被抛出,测试被取消 被认为已经成功了


您的用例有点令人费解,因为您的测试实际上没有做任何事情,并且没有您引用的bean。默认情况下,springbean是使用defaultscope=“singleton”属性声明的,因此如果您实际声明了一个bean,那么它将是一个缓存的singleton。但是,这与方法执行无关。

注意:“implements InitializingBean”使其成为一个bean。或者至少我假设你的名字。事实上,我可以@Autowire字段之类的东西。@BeforeClass的问题是它在Spring注入测试类之前执行。由于我喜欢注入测试资源,这通常是一个问题@Before和此类也在注入之前执行,但每次测试都执行。我发现最好的方法是使用InitiliazingBean接口中的AfterPropertieSet(),并使用注入资源进行任何必要的设置。我发现的问题是AfterPropertieSet是在每次测试之前运行的,这有点道理。在编辑代码以包含格式之前,我没有捕获代码的其余部分。我很确定,在使用BeanFactory之前,可以使用lazy init=“true”在@BeforeClass或@BeforeClass中按需实例化Spring,但这并不能解决重新初始化的问题。也许这只是我的观点,但我认为重新初始化不会有问题,除非有代码约束。更正我的评论:“@Before和诸如此类的也在注入之前执行”是不正确的。不过,我认为这一点在这个问题上变化不大。
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 26] DEBUG - Bean Initialized
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 17] DEBUG - Test1
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 26] DEBUG - Bean Initialized
2009-10-13 21:20:04,393 [TestAfterPropsSet.java 22] DEBUG - Test2