Spring 如何推迟调用@PostConstruct,直到jUnit具有设置测试上下文

Spring 如何推迟调用@PostConstruct,直到jUnit具有设置测试上下文,spring,reflection,junit,postconstruct,Spring,Reflection,Junit,Postconstruct,我有一个带有受保护的@PostConstruct方法的静态Spring3.2.4bean,该方法在初始化时从DB加载数据 在创建jUnit测试时,在我的测试方法中,我希望在DB中设置数据以适当地测试bean。然而,由于bean是在我的测试方法之前实例化的,我不知道如何请求Spring推迟bean的实例化,直到方法完成 考虑到@PostConstruct方法是受保护的,我不能直接调用它来重新初始化bean,除非我使用反射 是否有其他方法可以做到这一点,或者反射是唯一的方法?Spring是否有任何U

我有一个带有受保护的@PostConstruct方法的静态Spring3.2.4bean,该方法在初始化时从DB加载数据

在创建jUnit测试时,在我的测试方法中,我希望在DB中设置数据以适当地测试bean。然而,由于bean是在我的测试方法之前实例化的,我不知道如何请求Spring推迟bean的实例化,直到方法完成

考虑到@PostConstruct方法是受保护的,我不能直接调用它来重新初始化bean,除非我使用反射


是否有其他方法可以做到这一点,或者反射是唯一的方法?Spring是否有任何Util类来简化它,或者我必须使用标准java反射?

对于这种用例,您总是可以通过编程方式启动上下文。请注意,在本例中,您负责上下文的生命周期。以下伪代码说明了这一点:

@Test
public void yourTest() {
    // setup your database

    ConfigurableApplicationContext context =
        new ClassPathXmlApplicationContext("/org/foo/your-context.xml");
    // Or new AnnotationConfigApplicationContext(YourConfig.class)
    try {
        YourBean bean = context.getBean("beanId");
        // Assertions
    } finally {
        context.close();
    }
}
您可能需要Spring来初始化数据库。例如,您可以使用常规的Spring测试上下文支持来仅初始化数据库设置所需的bean,并以编程方式启动另一个上下文来断言您的服务。如果该上下文需要一些用于数据库初始化的服务,则可以启动子上下文,例如

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration // for instance FooTest-context.xml
public class FooTest {

    @Autowired
    private ApplicationContext mainContext;

    @Test
    public void yourTest() {
        // setup your database

        ClassPathXmlApplicationContext context =
                new ClassPathXmlApplicationContext();
        context.setParent(mainContext);
        context.setConfigLocation("/org/foo/your-context.xml");
        context.refresh();
        try {
            YourBean bean = context.getBean("beanId");
            // Assertions
        } finally {
            context.close();
        }
    }
}

如果这成为一个经常使用的用例,您可以创建一个模板方法来启动容器并调用回调接口。这样,您就可以在中心位置共享上下文生命周期管理。

谢谢。我最终解决了这个问题,但你的解决方案确实给了我另一种看待它的方式。