Java Autowire在junit测试中不工作

Java Autowire在junit测试中不工作,java,spring,junit,junit4,Java,Spring,Junit,Junit4,我肯定我错过了一些简单的东西。bar在junit测试中自动连接,但是为什么foo中的bar没有自动连接呢 @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"beans.xml"}) public class BarTest { @Autowired Object bar; @Test public void testBar() throws Exception {

我肯定我错过了一些简单的东西。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());
    }
}

Foo不是一个托管Springbean,您自己正在实例化它。所以Spring不会为您自动连接任何依赖项。

您只是在创建一个新的Foo实例。该实例不知道Spring依赖项注入容器。您必须在测试中自动连接foo:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"beans.xml"})
public class BarTest {  

    @Autowired
    // By the way, the by type autowire won't work properly here if you have
    // more instances of one type. If you named them  in your Spring
    // configuration use @Resource instead
    @Resource(name = "mybarobject")
    Object bar;
    @Autowired
    Foo foo;

    @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?
        assertEquals("expected", foo.someMethodThatUsesBar());
    }
}
你说的“酒吧里的食物”是什么意思?