如何在继承的XML配置中加载bean,在配置类中的bean之前(Spring中的集成测试)

时间:2015-08-07 17:22:57

标签: java spring dependency-injection integration-testing

在Spring中编写集成测试时,如何确保父上下文中的所有bean都先加载到其他bean中?

目前,我的层次结构中进一步下载的上下文类过早加载,导致空指针异常。

  • 我正在混合XML和@Configuration类

我的设置

我有一个抽象的测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"/persistence-context.xml"}) <-- My persistence layer contains my DAO classes
public abstract class MyBaseTest implements ApplicationContextAware { ... }

......我的实际考试是在一个具体的课程中:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
    @ContextConfiguration(classes = TestConfig.class)
})
public class MyTest extends MyBaseTest { 
@Autowired
MyDao myDao; // when I debug my code, I can see that this does not stay null - it gets loaded eventually!

... 
}

...需要来自我的TestConfig类的bean

@Import(value = {AnotherConfigClass.class})
@Configuration
public class TestConfig {

@Autowired
MyDAO myDAO; <-- this is null when loading classes


@Bean
public MyService myService() {
    MyService myService = new MyService();
    myService.setDAO(myDAO); <-- my DAO is null at this point!
    return myService;
}

...

}

...需要来自我的AdditionalConfig类的bean

@Configuration
public class AnotherConfigClass {

...

@PostConstruct
public void init() {

    myService.doSomethingUsingMyDAO(); <--- I need to use myService here, but a NPE is thrown.

1 个答案:

答案 0 :(得分:0)

AFAIK,基类上的注释不会在具体类上继承。您必须明确加载/persistence-context.xml

@RunWith(SpringJUnit4ClassRunner.class)
@ContextHierarchy({
    @ContextConfiguration(locations = {"/persistence-context.xml"}),
    @ContextConfiguration(classes = TestConfig.class)
})
public class MyTest extends MyBaseTest {
...