@Autowired annotation not working
I'm trying to test the Autowire option like this:
@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());
}
}
and the config file :
<?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>
But the Bar
object is not getting injected. Am I 开发者_运维知识库missing anything here or doing something wrong?
Note that I'm specifying the applicationContext file using annotation on the class.
If this is a unit-test, as it seems, add
@RunWith(SpringJUnit4ClassRunner.class)
And in your applicationContext.xml
don't forget this (although in this case it is not the problem)
<context:component-scan base="org.basepackage" />
The @ContextConfiguration attribute is part of the org.springframework.test
package, so isn't going to work in the manner you've attempted to use it. See this post on the Spring forums for more details.
精彩评论