【问题标题】:Using Autowired in a TestExecutionListener class for BeforeClass junit在 BeforeClass junit 的 TestExecutionListener 类中使用 Autowired
【发布时间】:2014-03-08 08:43:40
【问题描述】:
我需要在 junit 中执行 @BeforeClass 方法,但使用 Spring 注入值,因此无法将 private 变量切换到 static。我正在尝试执行此 Listeners 并创建一个 Listener 类,但我遇到了这个问题。
我在这个类中也有需要Autowire 的值,因为我要运行BeforeClass 的方法调用注入@Autowired 的变量。但是,由于某种原因,它不起作用,并且该值保持为空。有没有人遇到过这样的问题?
【问题讨论】:
标签:
java
spring
junit
listener
【解决方案1】:
这不是最干净的,但它有效:
public class MyTestListener extends AbstractTestExecutionListener {
@Value("${my.value}")
private String myValue;
@Autowired
private MyBean myBean;
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
testContext.getApplicationContext()
.getAutowireCapableBeanFactory()
.autowireBean(this);
}
}