我正在使用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() ;
}
}
答案 0 :(得分:4)
将SomeService
作为参数添加到构造函数,然后从字段中删除@Autowired
。现在不可能为空。
或者,将构造函数中的代码移动到@PostConstruct
方法中。
您应该阅读Running Setup Data on Startup in Spring。该指南首先列出您的代码,作为不执行此操作的示例。