崛起于Springboot2.X + 项目启动初始化方法(30)

《SpringBoot2.X心法总纲》mysql

      (本篇博客已于2019-08-28 优化更新)redis

      场景:证券、基金部分公司在本身业务活动项目启动以前都会将数据提早加载到redis中.sql

      CommandLineRunner 接口的Component 会在全部Spring Beans都初始化以后,SpringApplication.run()以前执行,很是适合在应用程序启动之初进行一些数据初始化的工做,ApplicationRunner为另一种初始化方法缓存

一、初始化类

@Component
public class MjtRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在这个方法里能够初始化数据,加载数据到缓存redis");
    }
}

      若是咱们须要将mysql等数据提早加载到redis中,能够实现这个类重写run方法。服务器

二、测试结果

      在启动类上添加验证启动顺序ide

@SpringBootApplication
public class Spring5Application {

    public static void main(String[] args) {
        System.out.println("111");
        SpringApplication.run(Spring5Application.class, args);
        System.out.println("2222");
    }
}

      只添加两行输出结果,启动以后,如图函数

三、编写多个初始化

      在类上添加@Order注解测试

@Component
@Order(1)
public class MjtRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在这个方法里能够初始化数据,加载数据到缓存redis");
    }
}
@Component
@Order(2)
public class TestRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("在这个方法里能够初始化数据,加载数据到缓存redis");
    }
}

      这样初始化的顺序就是从小到大的顺序执行。优化

四、第二种使用注解方法

@PostConstruct修饰的方法会在服务器加载Servle的时候运行,而且只会被服务器执行一次。PostConstruct在构造函数以后执行,init()方法以前执行。@PreDestroy()方法在destroy()方法执行执行以后执行,在方法上添加这两个注解也能够实现项目启动以前执行特定的方法。
相关文章
相关标签/搜索