今天开发中遇到的业务场景是:获取项目的版本号,在前端进行展示,所以需要用到在SpringBoot项目启动的时候自动调用程序中的方法,获取版本号信息,在百度上找到了两个可以进行项目启动执行指定方法的接口,一个是ApplicationRunner,另一个是 CommandLineRunner。 实现类需要覆写run方法,如果是遇到多个启动的方法,则需要指定调用的顺序,可以在类中多实现Order接口,覆写getOrder()方法,或者直接使用注解的方式,@Order(value = 1)。
上述两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。下面通过两个简单的例子,来看一下这两个接口的实现。
1、ApplicationRunner
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
@Order(value = 1)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments var1) throws Exception{
System.out.println("=====MyApplicationRunner class will be execute=====");
}
}
2、CommandLineRunner
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner, Ordered {
@Override
public int getOrder(){
return 1; //返回执行顺序
}
@Override
public void run(String... var1) throws Exception{
System.out.println("=====This will be execute =======");
}
}