gpt4 book ai didi

java - 在 BeforeClass junit 的 TestExecutionListener 类中使用 Autowiring

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:08:34 26 4
gpt4 key购买 nike

我需要在 junit 中执行一个 @BeforeClass 方法,但使用 Spring 注入(inject)值,因此无法将 private 变量切换为 static。我正在尝试执行此 Listeners 并创建一个 Listener 类,但我遇到了一个问题。

我在这个类中也有需要 Autowire 的值,因为我想运行 BeforeClass 的方法调用 @Autowired< 的变量 注入(inject)。但是,由于某种原因,它不起作用并且该值保持为空。有没有人遇到过这样的问题?

最佳答案

它不是最干净的,但它有效:

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);
}
}

关于java - 在 BeforeClass junit 的 TestExecutionListener 类中使用 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21687022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com