我正在尝试将对象注入到类中。但是,该字段始终为空。我试过@Autowired
和@Resource
注释。我不在任何地方用new
操作符创建对象。正确调用Foo
的构造函数。Spring bean被创建,但在Autowired时为null
这个问题的小例子:
Foo类
package foo.bar;
public class Foo {
Foo(){
System.out.println("Foo constructor");
}
public void func() {
System.out.println("func()");
}
}
酒吧类
package foo.bar;
public class Bar {
@Autowired
private Foo foo;
public Bar() {
foo.func();
}
}
切入点
package foo.bar;
public class HelloApp {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("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>
为什么现场的foo
Bar
类总是null
?我怎样才能解决这个问题?
构造函数被调用。因此调用foo.func();在Bar的构造函数中会产生一个NullPointer。你可以创建一个方法来调用foo.func();并用@PostConstruct对其进行注释以解决此问题 – Mick