为什么我的 bean 为空?
我正在尝试学习如何使用 applicationContext。我的目标是在使用单元测试时将模拟数据存储库替换为真实数据存储库。我不想明确地执行此操作,我想通过依赖项注入来执行此操作。
因此,在让事情变得复杂之前,作为一个简单的测试,我只是尝试从 applicationContext.xml 中获取一个 bean。根据我的阅读,这应该有效:
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
但我的 resultBean 始终为空。这是我的 applicationContext.xml,它位于 WebContent/WEB-INF 下:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="resultBean" name="resultBean" class="com.trgr.cobalt.company.domain.CompanyResult">
<property name="companyName">
<value>Microsoft</value>
</property>
</bean>
</beans>
那么为什么我的 resultBean 总是为 null?我做错了什么?
I am trying to learn how to use applicationContext. My goal is to swap out a mock data repository for a real one when using my unit tests. I don't want to do this explicitly, I want to do this with dependency injection.
So as a simple test before I make things complicated, I'm simply trying to get a bean out of my applicationContext.xml. From what I've read, this should work:
@ContextConfiguration(locations = "/applicationContext.xml")
public class ResultsListTests {
@Resource
CompanyResult resultBean;
@Test
public void shouldAddResults() {
assertEquals(resultBean.getCompanyName(), "Microsoft");
But my resultBean is always null. Here is my applicationContext.xml, which is located under WebContent/WEB-INF:
<?xml version="1.0" encoding="UTF-8"?>
<beans>
<bean id="resultBean" name="resultBean" class="com.trgr.cobalt.company.domain.CompanyResult">
<property name="companyName">
<value>Microsoft</value>
</property>
</bean>
</beans>
So why is my resultBean always null? What have I done incorrectly?
您缺少
@RunWith(SpringJUnit4ClassRunner.class)
注释:BTW,在您的示例中,
WebContent/WEB-INF
不是正确的位置对于applicationContext.xml
。如果您指定@ContextConfiguration(locations = "/applicationContext.xml"),那么Spring将在类路径的根目录中查找
applicationContext.xml
,而不是在WebContent中/WEB-INF
(jUnit 100% 不知道这是一个 Web 应用程序)。了解更多信息,请参阅Spring 参考文档。
You are missing a
@RunWith(SpringJUnit4ClassRunner.class)
annotation:BTW, in your sample,
WebContent/WEB-INF
is not the proper location forapplicationContext.xml
.If you specify
@ContextConfiguration(locations = "/applicationContext.xml")
then Spring will look forapplicationContext.xml
at the root of the classpath, not inWebContent/WEB-INF
(jUnit is 100% unaware of the fact that this is a web application).For more information, see Spring reference documentation.