@PostConstruct 是一种初始化形式
以下述代码为例
- TestController 中成员变量 testService 被 @Autowired 润饰
- TestService 将会在 TestController 构造方法执行后注入
@Component
public class TestService {public TestService() {System.out.println("TestService construct");
}
public void init() {System.out.println("TestService init");
}
}
@RestController
public class TestController {
@Autowired
private TestService testService;
public TestController() {System.out.println("TestController construct");
testService.init();}
}
此时启动 Spring 利用,则会呈现报错,其起因就是 testService 在执行 TestController 构造方法时并没有实现初始化和注入;
TestController 初始化时须要执行依赖中的办法时,这种写法就会引起问题;
此时就能够应用 @PostConstruct 来解决问题
Caused by: java.lang.NullPointerException: null
at com.example.demo.my.view.TestController.<init>(TestController.java:20) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:na]
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490) ~[na:na]
调整代码后
@RestController
public class TestController {
@Autowired
private TestService testService;
public TestController() {System.out.println("TestController construct");
}
@PostConstruct
public void initBeforeConstruct() {System.out.println("TestController PostConstruct");
testService.init();}
}
此时启动输入后果
从中可见总体的执行程序
- 构造方法
- @Autowird
- @PostConstruct