春季dependency injectionSpring TestExecutionListeners无法正常工作

我怎样才能将Springdependency injection到我写的扩展AbstractTestExecutionListener的TestExecutionListener类中?

Spring DI似乎不适用于TestExecutionListener类。 问题示例:

AbstractTestExecutionListener:

class SimpleClassTestListener extends AbstractTestExecutionListener { @Autowired protected String simplefield; // does not work simplefield = null @Override public void beforeTestClass(TestContext testContext) throws Exception { System.out.println("simplefield " + simplefield); } } 

配置文件:

 @Configuration @ComponentScan(basePackages = { "com.example*" }) class SimpleConfig { @Bean public String simpleField() { return "simpleField"; } } 

JUnit测试文件:

 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { SimpleConfig.class }) @TestExecutionListeners(mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS, listeners = { SimpleClassTestListener.class }) public class SimpleTest { @Test public void test(){ assertTrue(); } } 

正如代码注释中所强调的,当我运行它时,它将打印“simplefield null”,因为simplefield永远不会被注入一个值。

只需为整个TestExecutionListener添加自动assembly。

 @Override public void beforeTestClass(TestContext testContext) throws Exception { testContext.getApplicationContext() .getAutowireCapableBeanFactory() .autowireBean(this); // your code that uses autowired fields } 

检查github中的示例项目 。