【问题标题】:How to access spring ApplicationContext in junit @BeforeClass static method?如何在junit @BeforeClass静态方法中访问spring ApplicationContext?
【发布时间】:2015-04-07 16:37:57
【问题描述】:

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

private static ApplicationContext applicationContext;
@Autowired
    public static void setApplicationContext(ApplicationContext applicationContext) {
        AuditorTest.applicationContext = applicationContext;
    }

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

如何自动连接静态ApplicationContext

【问题讨论】:

  • 为什么需要这样做?
  • 在 jUnit 测试之前填充数据库?
  • 您需要为整个测试用例填充一次吗?
  • @VolodymyrLevytskyi 你在使用 spring 嵌入式数据库支持吗?

标签: java spring


【解决方案1】:

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

@Autowired
public void setApplicationContext(ApplicationContext applicationContext) {
    AuditorTest.applicationContext = applicationContext;
}

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

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

【讨论】:

  • 此解决方案适用于访问上下文,但如果您在@BeforeClass 中需要它,那么您无法访问非静态变量。当您有一个在初始化时访问 Context 的 Bean 类时,您需要这个。
【解决方案2】:

您现在可能已经找到了解决方法。 在这里可以帮助其他人。

我遇到了类似的问题。大多数spring框架选项 provided 不允许静态访问 ApplicationContext。

解决方法很简单。使用创建您自己的 ApplicationContext ClassPathXmlApplicationContext 使用 bean 配置但静态。

<code>
public class BaseTestCase {
    static {
        ApplicationContext context = new ClassPathXmlApplicationContext("test-config.xml"); 
             // Do what you want to do with the context
             // Probably store in static variable to access somewhere else
         }  
    }
</code>

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多