@Autowired 注释不起作用
我正在尝试像这样测试 Autowire 选项:
@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 文件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果这是一个单元测试,就像看起来一样,请
在您的
applicationContext.xml
中添加 And 不要忘记这一点(尽管在这种情况下这不是问题)If this is a unit-test, as it seems, add
And in your
applicationContext.xml
don't forget this (although in this case it is not the problem)@ContextConfiguration 属性是 org.springframework.test 包的一部分,因此不会以您尝试使用它的方式工作。有关更多详细信息,请参阅 Spring 论坛上的这篇文章。
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.