我正在嘗試將對象注入到類中。但是,該字段始終爲空。我試過@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