如果在Application运行之前需要执行一些代码,可以通过实现ApplicationRunner或者CommandLineRunner接口。接口只有一个run方法,会在SpringApplication.run(...)方法执行之前运行。其中ApplicationRunner可以访问ApplicationArguments参数信息;而CommandLineRunner可以访问原始的String[]参数。
如果实现接口的类有多个,还可以通过实现org.springframework.core.Ordered接口或则使用@Order(value=int_value)来控制执行顺序,int值越小优先级越高,默认值为Ordered.LOWEST_PRECEDENCE(2147483647)。
1,实现ApplicationRunner接口,并实现Ordered接口执行顺序
@Component
public class MyRunnerImplAppRunner implements ApplicationRunner,Ordered{
@Override
public void run(ApplicationArguments args) throws Exception {
// TODO Auto-generated method stub
System.out.println(this.getClass().getName()+" runs before application running");
System.out.println("args ares "+args.getSourceArgs().toString());
}
@Override
public int getOrder() {
// TODO Auto-generated method stub
return 1;
}
}
2,实现CommandLineRunner接口,使用@Order注解指定运行顺序
@Component
@Order(value=4)
public class MyRunnerImplCmdRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println(this.getClass().getName()+" running before application running");
System.out.println("args are "+args.toString());
}
}
运行结果: