2010-09-10 86 views
1

我想测试的Autowire选项是这样的:@Autowired注解不工作

@ContextConfiguration(locations = { "classpath:applnContext.xml" }) 
public class Foo { 
    @Autowired 
    private Bar bar; 

    public Bar getBar() { 
     return bar; 
    } 

    public void setBar(final Bar bar) { 
     this.bar = bar; 
    } 

    public static void main(final String[] args) { 
     final Foo f = new Foo(); 
     System.out.println(f.getBar()); 
    } 
} 

和配置文件:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <bean id="bar" class="entity.Bar"></bean> 
    <context:annotation-config /> 

</beans> 

Bar对象没有被注入。我在这里错过什么或做错了什么?

请注意,我在该类上使用注释指定了applicationContext文件。

回答

2

@ContextConfiguration属性是org.springframework.test程序包的一部分,因此不会按照您尝试使用它的方式工作。有关更多详细信息,请参见Spring论坛上的this post

4

如果这是一个单元测试,因为它似乎,添加

@RunWith(SpringJUnit4ClassRunner.class) 

而在你applicationContext.xml不要忘记这一点(虽然在这种情况下,它是没有问题的)

<context:component-scan base="org.basepackage" />