2021-03-14-SpringBoot项目在启动的时候执行其它代码

前言

  • 在挺多时候我们都需要在项目启动的同时执行一些其它的代码
  • 下面讲一些SpringBoot项目如何实现的

方式一

  • 实现ApplicationRunner接口
@Component
public class RunUtilTest  implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(1111);

    }
}

方式二

  • 实现CommandLineRunner接口
  • 两个接口的区别就是传入的参数不一样,不过传入的参数我们一般不需要用到,所以这两个方式其实一个效果
@Component
public class RunUtilTest2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(2133254);
    }
}

@Order注解

  • 加在类上,注解的value值越小,越先执行
  • 例如下面代码就是RunUtilTest2先执行
@Component
@Order(value=1)
public class RunUtilTest2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(2133254);
    }
}




@Component
@Order(value=2)
public class RunUtilTest  implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(1111);

    }
}

猜你喜欢

转载自blog.csdn.net/qq_41270550/article/details/113983372
今日推荐