Spring Boot bean初始化顺序

时间:2019-08-20 22:51:54

标签: java spring spring-boot

我正在使用Spring Boot开发一个简单的REST API,但是我坚持使用spring来初始化应用程序bean的命令。如何在应用程序中控制Bean初始化的顺序?

我使用的是Spring Boot 2.1.7,问题是Spring尝试在ContactRestController依赖的SomeService之前初始化ContactRestController,因此它最终在ContactRestController的构造函数中出现NullPointerException:

@RestController
public class ContactRestController {
    @Autowired
    private SomeService ;
   // no-args constructor 

    public ContactRestControlle(){
       this.someService.doStuff() ;
    }
}

1 个答案:

答案 0 :(得分:4)

SomeService作为参数添加到构造函数,然后从字段中删除@Autowired。现在不可能为空。

或者,将构造函数中的代码移动到@PostConstruct方法中。

您应该阅读Running Setup Data on Startup in Spring。该指南首先列出您的代码,作为不执行此操作的示例。