且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

运行测试用例时,Spring依赖项注入为空

更新时间:2023-11-19 23:31:34

您的配置无法正常工作,因为Spring不会创建JUnit使用的ExtractorTest实例.而是由JUnit创建实例,然后将其传递给Spring进行后期处理.

Your configuration doesn't work because Spring doesn't create the instance of ExtractorTest which JUnit uses; instead the instance is created by JUnit and then passed to Spring for post processing.

您看到的效果是因为应用程序上下文创建了一个ID为ExtractorTest的bean,但是没有人使用它.

The effect you see is because the application context creates a bean with the id ExtractorTest but nobody ever uses that.

伪代码:

ApplicationContect appContext = new ...
appContext.defineBean("ExtractorTest", new ExtractorTest()); // Calls setter

ExtractorTest test = new ExtractorTest(); // Doesn't call setter
test.postProcess(appContext); // inject beans from appContext -> does nothing in your case

所以解决方案是定义一个bean file:

So the solution is to define a bean file:

<bean id="file" class="..." />

(请参阅文档,了解如何构建Resource bean),然后让Spring注入它:

(see the documentation how to build a Resource bean) and then let Spring inject that:

@Autowired
private Resource file;