SringBoot启动加载 CommandLineRunner @PostConstruct

CommandLineRunner
在项目中,经常有这样的需求,我们需要在项目启动完立即初始化一些数据(比如缓存等),以便后面调用使用。spring boot可以通过CommandLineRunner接口实现启动加载功能。

新建一个Java文件,类需要用Component声明下,需要实现CommandLineRunner接口,然后重写run方法,在run方法内编写需要加载的内容。代码如下:

@Component
public class InitStarter implements CommandLineRunner{
    
    
    @Override
    public void run(String... args) throws Exception {
    
    
        System.out.println("CommandLineRunner example start");
    }
}

启动项目,运行结果证明:CommandLineRunner会在服务启动之后被立即执行
在这里插入图片描述
在项目中,我们可以写一个类继承CommandLineRunner接口,然后在实现方法中写多个需要加载的方法,也可以写多个类继承CommandLineRunner,这些类之间,可以通过order注解(@Order(value=1))实现先后顺序。
例子如下:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
总结:
CommandLineRunner会在服务启动之后被立即执行。
CommandLineRunner可以有多个,且多个直接可以用order注解进行排序。

@PostConstruct
另一个需求是,在类加载的时候,为当前类初始化一些数据,那么可以使用@PostConstruct注解。
Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。
在一个类内,如果有构造器(Constructor ),有@PostConstruct,还有@Autowired,他们的先后执行顺序为Constructor >> @Autowired >> @PostConstruct。
因为一个有声明注解的类文件(必须有声明,这样在项目初始化时候才会注入),在项目启动后,会对对象进行依赖注入,而初始化的动作会依赖于对象,所以假象上看,也类似于项目启动就会执行的操作,因此,我们也可以通过这样的形式,对数据进行初始化。
说明一下,@PostConstruct更针对性于当前类文件,而CommandLineRunner更服务于整个项目。所以在我们使用中,可根据自己的使用场景来进行选择用这两种方式来实现初始化。

@Component
public class Init {
    
    
    @PostConstruct
    private void init(){
    
    
        System.out.println("PostConstruct 注解 初始化数据.");
    }
}

执行结果:
在这里插入图片描述
说明一下:执行结果可以看到,在项目还没有启动成功的时候,@PostConstruct已经执行完了,因为@PostConstruct是在Init类注入完成后立马执行的,它并不依赖于项目的启动。
原文链接

扫码关注我的微信公众号
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/CharlesYooSky/article/details/105865040