欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

23.8 Using the ApplicationRunner or CommandLineRunner 实现ApplicationRunner 和CommandLineRunner

程序员文章站 2022-04-28 22:51:01
...

如果您需要在SpringApplication启动之后运行一些特定的代码,那么您可以实现ApplicationRunner或commandlinrun 接口。这两个接口都以相同的方式工作,并提供一个单独的运行方法,在springapplication.run(.)完成之前,它将被调用。

CommandLineRunner接口提供对应用程序参数的访问,作为一个简单的字符串数组,ApplicationRunner提供了ApplicationArguments。

执行顺序在SpringApplication启动之前,在大部分监听器之后。监听器可参考前面的文章。

ApplicationRunner实现

@SpringBootApplication
public class MyApplicationRunner {
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners(new ApplicationListenerStarted());
        application.addListeners(new ApplicationListenerEnvironmentPrepared());
        application.addListeners(new ApplicationListenerPrepared());
        application.addListeners(new ApplicationListenerReadyEvent());
        application.addListeners(new ApplicationListenerFailed());
        application.run(args);
    }
}

@Order(2)
@Component
class MyApplicationRunner1 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        StringBuffer sf =new StringBuffer("");
        for(String str :applicationArguments.getSourceArgs()){
            sf.append(str);
        }
        System.out.println("-------------------" + this.toString()+"----"+sf);
    }
}

@Order(1)
@Component
class MyApplicationRunner2 implements ApplicationRunner  {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("-------------------" + this.toString());
    }


}

CommandLineRunner实现

@SpringBootApplication
public class MyCommandLineRunner {
    public static void main(String[] args) {
        String[] aa ={"0","1"};
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners(new ApplicationListenerStarted());
        application.addListeners(new ApplicationListenerEnvironmentPrepared());
        application.addListeners(new ApplicationListenerPrepared());
        application.addListeners(new ApplicationListenerReadyEvent());
        application.addListeners(new ApplicationListenerFailed());
        application.run(aa);
    }
}

@Order(2)
@Component
class MyCommandLineRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        StringBuffer sf =new StringBuffer("");
        for(String str :args){
            sf.append(str);
        }
        System.out.println("-------------------" + this.toString()+ "---"+sf);

    }
}

@Order(1)
@Component
class MyCommandLineRunner2 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("-------------------" + this.toString());
    }


当有对个实现可以使用@Order进行排序执行