我不明白弹簧靴注释@Autowired
是如何正确工作的。这是一个简单的例子:
@SpringBootApplication
public class App {
@Autowired
public Starter starter;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("init App");
//starter.init();
}
}
-
@Repository
public class Starter {
public Starter() {System.out.println("init Starter");}
public void init() { System.out.println("call init"); }
}
当我执行此代码时,我会得到日志init App
和init Starter
,因此Spring会创建此对象。但是当我从Starter
中的App
调用init方法时,我得到NullPointerException
。是否还需要使用注释@Autowired
来初始化我的对象?
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [{package}.App$$EnhancerBySpringCGLIB$$87a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException
答案 0 :(得分:24)
当您从类init
的构造函数调用App
方法时,Spring尚未将依赖项自动装入App
对象。如果要在Spring完成创建并自动装配App
对象后调用此方法,请添加一个带有@PostConstruct
注释的方法来执行此操作,例如:
@SpringBootApplication
public class App {
@Autowired
public Starter starter;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("constructor of App");
}
@PostConstruct
public void init() {
System.out.println("Calling starter.init");
starter.init();
}
}