了解Spring Boot @Autowired

我不明白弹簧靴注释@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 Appinit Starter ,所以spring创建了这个对象。 但是当我从App Starter调用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 

当您从类App的构造函数中调用init方法时,Spring尚未将依赖项自动assembly到App对象中。 如果要在Spring完成创建并自动assemblyApp对象后调用此方法,则添加带有@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(); } }