如果你希望在SpringApplication启动后立刻执行特定任务,可以实现ApplicationRunner,CommandLineRunner 中任意接口(这也是Spring官方推荐的方式,而不是使用监听Spring的生命周期事件)。 这两个接口都只有一个run 方法,都是在SpringApplication.run 方法完成之前调用,ApplicationRunner 和 CommandLineRunner 的执行顺序可以通过@Order指定,如下代码所示
ApplicationRunner:
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("this is MyApplicationRunner executed.");
}
}
CommandLineRunner:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(2)
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("this is MyCommandLineRunner executed.");
}
}
运行主函数
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
@SpringBootApplication
public class Example {
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
}
执行结果:
ApplicationRunner 与 CommandLineRunner 的区别为 run 函数的参数不一样,CommandLineRunner 中run函数的参数为命令行传过来的原始参数,ApplicationRunner 中的run函数参数则使用了 ApplicationArguments 进行封装,日常开发中如果希望获取到命令行参数也可以直接 @autowired ApplicationArguments 进行注入。
如下:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@SpringBootApplication
public class Example {
@Autowired
private ApplicationArguments applicationArguments;
public static void main(String[] args) {
SpringApplication.run(Example.class, args);
}
@RequestMapping("/")
String home() {
List<String> myValue=applicationArguments.getOptionValues( "MyValue" );
return "ApplicationArguments:获取参数为"+myValue;
}
}
配置命令行参数:
运行结果如下:
各位 未来的 IT精英,文章内容个人整理验证通过,仅供参考,如果文章有任何错误,希望指正,一起探讨交流,如果文章对你有帮助,感谢 点赞 鼓励,谢谢。转载希望表明出处