在我正在处理的 Spring Boot 应用程序中,我有一个未注释为 bean (@Component
) 的类,但包含一个 Autowiring 字段:
public class One{
@Autowired
private Two x;
public getX(){
return x;
}
}
在 Spring 应用程序的配置 xml 中,类 One
被标记为 bean,这使得变量 x
在我运行应用程序时得到初始化。
现在自己写了个测试好像没有使用spring xml配置。所以我尝试手动完成:
@RunWith(SpringRunner.class)
public class Test{
@Autowired
One y;
@Test
public void checkOne(){
System.out.println(y.getX()); //null
}
}
如何让 Spring 注入(inject)正确的代码,使 x
在我的测试中不为空?
最佳答案
只需告诉测试使用什么配置即可:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext_test.xml" })
public class Test{
@Autowired
One y;
@Test
public void checkOne(){
System.out.println(y.getX()); //null
}
}
参见 here对于文档
关于java - 我如何以编程方式 Autowiring 不属于 bean 的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48745065/