CommandLineRunner,ApplicationRunner

helloworld

 

springboot项目启动之后初始化自定义配置类

前言

今天在写项目的时候,需要再springboot项目启动之后,加载我自定义的配置类的一些方法,百度了之后特此记录下。

正文

方法有两种:

1、 创建自定义类实现 CommandLineRunner接口,重写run()方法。springboot启动之后会默认去扫描所有实现了CommandLineRunner的类,并运行其run()方法。

复制代码

@Component
@Order(2)   //通过order值的大小来决定启动的顺序
public class AskForLeave implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        askForLeave();
    }

    public void askForLeave(){
        System.out.println("项目启动了,执行了方法");
    }
}

复制代码

运行结果:

 2、创建自定义类实现ApplicationRunner 接口,重写run()方法。

复制代码

@Component
@Order(3)
public class Hello implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {

        hello();
    }

    public void hello(){
        System.out.println("项目又启动了,这次使用的是:继承 ApplicationRunner");
    }
}

复制代码

结果如下:

关于二者的区别:

其实并没有什么区别,如果想获取更加详细的参数的时候,可以选择使用ApplicationRunner接口。其参数类型为:ApplicationArguments 。

猜你喜欢

转载自blog.csdn.net/CC919026304/article/details/83828261