【发布时间】:2014-10-20 09:58:26
【问题描述】:
我使用过 JUnit,但有些测试存在一些问题,这些测试在 Spring bean 中有 @Autowired 注释,当我引用它们时,@Autowired 的 bean 始终为 NULL。
示例代码如下:
public class Test {
protected ApplicationContext ac;
@Before
public void setUp() {
ac = new FileSystemXmlApplicationContext("classpath:config/applicationContext.xml"
"classpath:config/test-datasources.xml");
}
@Test
public void testRun() throws Exception {
IManager manager = (IManager)this.ac.getBean("manager");
manager.doSomething();
}
}
@Service
public class Manager implements IManager {
public boolean doSomething() throws Exception {
ParametersJCSCache parametersJCSCache = new ParametersJCSCache();
String paramValue = parametersJCSCache.getParameter("XPTO");
...
}
}
public class ParametersJCSCache extends SpringBeanAutowiringSupport {
@Autowired
private IParameterManager parameterManager; //THIS IS NULL
}
在调用 Manager 对象时,Spring 会生成代理,但在访问 @Autowired parameterManager 时,该对象为空,因此我无法测试此方法。
知道是什么原因造成的吗?为什么对象没有被注入?它在 Web 应用程序的上下文中运行良好,但在测试上下文中始终为 NULL。
【问题讨论】:
标签: java spring junit autowired