如何在junit @BeforeClass静态方法中访问spring ApplicationContext?

Vol*_*kyi 5 java spring

我试图通过以下方式获得它:

private static ApplicationContext applicationContext;
@Autowired
    public static void setApplicationContext(ApplicationContext applicationContext) {
        AuditorTest.applicationContext = applicationContext;
    }
Run Code Online (Sandbox Code Playgroud)

但这并不能像其他所有尝试一样起作用。

如何自动连接静电ApplicationContext

Roh*_*ain 5

您不能在static方法上自动装配 spring bean 。您必须改为将其设为实例方法,并让它将值分配给static变量(这样可以正常工作):

@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
    AuditorTest.applicationContext = applicationContext;
}
Run Code Online (Sandbox Code Playgroud)

但我不认为这就是你想要的。我想你应该用SpringJUnitRunner, 和注释测试类@ContextConfiguration,然后你就可以在ApplicationContext那里自动装配:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)  // configuration location
public class TestClass {
    @Autowired
    private ApplicationContext context;
}
Run Code Online (Sandbox Code Playgroud)

  • 该解决方案适用于访问上下文,但是如果您在 @BeforeClass 中需要它,那么您将无法访问非静态变量。当您有一个在初始化时访问 Context 的 Bean 类时,您需要这个。 (3认同)