java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot启动加载CommandLineRunner @PostConstruct

springboot启动加载CommandLineRunner @PostConstruct问题

作者:大旭123456

这篇文章主要介绍了springboot启动加载CommandLineRunner @PostConstruct问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

springboot 启动加载

CommandLineRunner

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

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

代码如下:

package com.study.test.startup;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Description: 初始化启动类
 * @Author: chen
 * @Date: Created in 2019/2/22
 */
@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))实现先后顺序。

例子如下:

总结:

@PostConstruct

另一个需求是,在类加载的时候,为当前类初始化一些数据,那么可以使用@PostConstruct注解。

Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy,这两个注解被用来修饰一个非静态的void()方法。

在一个类内,如果有构造器(Constructor ),有@PostConstruct,还有@Autowired,他们的先后执行顺序为Constructor >> @Autowired >> @PostConstruct。

因为一个有声明注解的类文件(必须有声明,这样在项目初始化时候才会注入),在项目启动后,会对对象进行依赖注入,而初始化的动作会依赖于对象,所以假象上看,也类似于项目启动就会执行的操作,因此,我们也可以通过这样的形式,对数据进行初始化。

说明一下:

@PostConstruct更针对性于当前类文件,而CommandLineRunner更服务于整个项目。所以在我们使用中,可根据自己的使用场景来进行选择用这两种方式来实现初始化。

package com.study.test.postConstruct;

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Description:
 * @Author: chen
 * @Date: Created in 2019/2/25
 */
@Component
public class Init {

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

执行结果:

说明一下:

执行结果可以看到,在项目还没有启动成功的时候,@PostConstruct已经执行完了,因为@PostConstruct是在Init类注入完成后立马执行的,它并不依赖于项目的启动。

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文