[英]Spring bean is created, but is null when Autowired
I am trying to inject an object to a class. 我正在尝试将一个对象注入一个类。 However, the field is always null. 但是,该字段始终为null。 I tried @Autowired
and @Resource
annotations. 我试过@Autowired
和@Resource
注释。 I am not creating the object with new
operator anywhere. 我不是在任何地方使用new
运算符创建对象。 The constructor of Foo
is called properly. Foo
的构造函数被正确调用。
The minimal example of this problem: 这个问题的最小例子:
Foo class Foo类
package foo.bar;
public class Foo {
Foo(){
System.out.println("Foo constructor");
}
public void func() {
System.out.println("func()");
}
}
Bar class 酒吧课
package foo.bar;
public class Bar {
@Autowired
private Foo foo;
public Bar() {
foo.func();
}
}
Entry point 入口点
package foo.bar;
public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");
}
}
spring-config.xml 春天-config.xml中
<?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.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="foo.bar"/>
<bean id = "foo" class="foo.bar.Foo" />
<bean id = "bar" class="foo.bar.Bar" />
</beans>
Why is foo
field of Bar
class always null
? 为什么Bar
类的foo
字段始终为null
? How can I fix this? 我怎样才能解决这个问题?
As @Mick pointed out, field injection necessarily takes place after the constructor is finished (there's no other way for Spring to see the instance and manipulate it). 正如@Mick指出的那样,必须在构造函数完成后进行字段注入(Spring没有其他方法可以查看实例并对其进行操作)。 Modify your class to use constructor injection, and you'll both make your dependencies more explicit (and thus easier to test, for example) and eliminate what's essentially a race condition: 修改你的类以使用构造函数注入,你将使你的依赖项更加明确(例如,更容易测试)并消除基本上是竞争条件:
public class Bar {
private Foo foo;
@Autowired
public Bar(Foo foo) {
this.foo = foo;
foo.func();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.