如果在容器启动的时候需要读取配置文件或者数据库连接等操作,可以使用这两个接口来实现。
这两个接口分别为CommandLineRunner和ApplicationRunner,它们是在容器启动成功后的最后一步回调。
可以有多个实现,可以通过@Order(index)注解或Ordered接口来控制执行顺序,数字小的先执行,没有@Order注解的最后执行
如果同时存在ApplicationRunner和CommandLineRunner接口实现,并且@Order注解index相同,则优先执行ApplicationRunner的接口实现。
区别:方法的参数不一样:
CommandLineRunner是最原始的参数,没有做任何处理;
ApplicationRunner的参数是ApplicationArguments,对原始参数做了进一步的封装。
接口源码:
public interface CommandLineRunner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
void run(String... args) throws Exception;
}
public interface ApplicationRunner {
/**
* Callback used to run the bean.
* @param args incoming application arguments
* @throws Exception on error
*/
void run(ApplicationArguments args) throws Exception;
}
CommandLineRunner
1.实现CommandLineRunner接口
package com.alongwu.spring;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(1)
@Component
public class ServerStartedReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("应用已经成功启动!");
}
}
package com.alongwu.spring;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Order(2)
@Component
public class ServerSuccessReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("App start!");
}
}
2. 纳入到spring容器中管理
可以使用@Component注解的方式或其它方式
ApplicationRunner
package com.alongwu.spring;
import java.util.Arrays;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class StartedApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("应用已经启动,启动参数为:"+Arrays.asList(args.getSourceArgs()));
}
}
这里传入了两个参数 aa , bb
package com.alongwu.spring;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
ConfigurableApplicationContext context = app.run("aa","bb");
context.close();
}
}
运行结果:
应用已经成功启动!
App start!
应用已经启动,启动参数为:[aa, bb]