CommandLineRunner 与 @PostConstruct的区别 应用场景

@PostConstruct 要比实现CommandLineRunner的类加载的要早

CommandLineRunner 是在项目启动完之后加载

比如我们对数据初始化的时候, 用到了其他的Service

如果用@PostConstruct 使用这个service可能会空指针异常, 以为@PostConstruct修饰的方法加载的早, 用到的那个service此时还未加载到spring容器中

举例子

 

改为CommandLineRunner 

  

猜你喜欢

转载自blog.csdn.net/weixin_44912855/article/details/119797954