2011-01-14 25 views
7

私は単純なものがないと確信しています。バーはjunitテストでautowiredになりますが、なぜfooのバーは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は管理されたスプリングBeanではなく、自分でインスタンス化しています。だから、Springはあなたのために依存関係のいずれかをautowireにしません。

+2

heh。ああ、私は睡眠が必要です。それはとても明らかです。ありがとう! – Upgradingdave

7

あなたはFooの新しいインスタンスを作成しています。この例では、Spring依存性注入コンテナについては考えていません。

@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

関連する問題