2011-01-14 7 views
7

나는 간단한 것을 놓치고 싶습니다. bar는 junit 테스트에서 자동으로 실행되지만, foo 내부의 bar는 autowired가되지 않는 이유는 무엇입니까?junit 테스트에서 Autowire가 작동하지 않습니다.

@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()); 
    } 
} 
+0

"bar inside foo"는 무엇을 의미합니까? – skaffman

답변

12

Foo는 관리되는 스프링 빈이 아니므로 직접 인스턴스를 생성해야합니다. 그래서 Spring은 당신을 위해 의존성을 autowire하지 않을 것입니다.

+2

ㅎ 오, 나는 잠이 필요해. 그건 아주 분명해. 감사! – Upgradingdave

7

방금 ​​Foo의 새 인스턴스를 만들고 있습니다. 이 인스턴스는 Spring 의존성 주입 컨테이너에 대해 전혀 모른다. 테스트에서 foo를 autowire해야합니다.

@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()); 
    } 
} 
+0

은 완벽한 의미를가집니다. – Upgradingdave

관련 문제