【问题标题】:How to load beans in inherited XML config, before beans in Configuration classes (integration tests in Spring)如何在配置类中的 bean 之前在继承的 XML 配置中加载 bean(Spring 中的集成测试)
【发布时间】:2026-02-04 02:15:02
【问题描述】:

在 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.

【问题讨论】:

    标签: java spring dependency-injection integration-testing


    【解决方案1】:

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

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

    【讨论】:

      最近更新 更多