1

@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();
    }
}

此时启动输出结果
image.png
从中可见总体的执行顺序

  1. 构造方法
  2. @Autowird
  3. @PostConstruct

老污的猫
30 声望5 粉丝