SpringBoot - CommandLineRunner接口 - 初始化操作

目录

前言

CommandLineRunner接口在容器启动成功后最后一步调用,常用于应用程序启动后初始化操作,其在整个应用生命周期内只会执行一次。


具体应用

实现CommandLineRunner接口

  • Runner.java
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class Runner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        /**
         * TODO:
         */
        System.out.println(" Runner run ");
    }
}
  • CommandLineRunner会在Spring Boot容器加载之后执行

SpringBoot - CommandLineRunner接口 - 初始化操作


CommandLineRunner实现类的执行顺序

  • 使用@Order注解定义CommandLineRunner的执行顺序
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(1)
public class RunnerOne implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        /**
         * TODO:
         */
        System.out.println(" RunnerOne run ");
    }
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(2)
public class RunnerTwo implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        /**
         * TODO:
         */
        System.out.println(" RunnerTwo run ");
    }
}

SpringBoot - CommandLineRunner接口 - 初始化操作


- End -
梦想是咸鱼
关注一下吧
SpringBoot - CommandLineRunner接口 - 初始化操作
上一篇:Oracle 11g+Windows10 x64安装、配置过程记录


下一篇:Spring Boot CommandLineRunner