Autowire 在 junit 测试中不起作用
我确信我错过了一些简单的事情。 bar 在 junit 测试中被自动装配,但为什么 foo 内的 bar 没有被自动装配?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {
@Autowired
Object bar;
@Test
public void testBar() throws Exception {
//this works
assertEquals("expected", bar.someMethod());
//this doesn't work, because the bar object inside foo isn't autowired?
Foo foo = new Foo();
assertEquals("expected", foo.someMethodThatUsesBar());
}
}
I'm sure I'm missing something simple. bar gets autowired in the junit test, but why doesn't bar inside foo get autowired?
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {
@Autowired
Object bar;
@Test
public void testBar() throws Exception {
//this works
assertEquals("expected", bar.someMethod());
//this doesn't work, because the bar object inside foo isn't autowired?
Foo foo = new Foo();
assertEquals("expected", foo.someMethodThatUsesBar());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Foo 不是托管 spring bean,您自己实例化它。因此 Spring 不会为您自动装配任何依赖项。
Foo isn't a managed spring bean, you are instantiating it yourself. So Spring's not going to autowire any of its dependencies for you.
您只是创建 Foo 的一个新实例。该实例不知道 Spring 依赖注入容器。您必须在测试中自动装配 foo:
You are just creating a new instance of Foo. That instance has no idea about the Spring dependency injection container. You have to autowire foo in your test: