前言
有些项目场景,我们需要在springboot启动后加载一些特别的业务数据,或者打印相关的项目信息,本文介绍springboot启动后执行代码简单示例
正文
Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。
这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。
- ApplicationRunner 是使用ApplicationArguments 用来接收参数的
- CommandLineRunner 接口可以用来接收字符串数组的命令行参数
示例:ApplicationRunner
场景:项目启动后,在日志中打印项目访问地址,便于研发阶段快速访问相关地址
@Component
@Order(1)//如果多个自定义ApplicationRunner,用来标明执行顺序
public class ShowInfoApplicationRunner implements ApplicationRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(ShowInfoApplicationRunner.class);
@Autowired
private TomcatServletWebServerFactory tomcatServletWebServerFactory;
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
this.showUrl();
}
private void showUrl() throws Exception{
String host = InetAddress.getLocalHost().getHostAddress();
int port = tomcatServletWebServerFactory.getPort();
String contextPath = tomcatServletWebServerFactory.getContextPath();
String protocol = tomcatServletWebServerFactory.getSsl() != null ? "https://" : "http://";
String address = protocol + host + ":" + port + contextPath+"/";
LOGGER.info("欢迎访问:{}", address);
LOGGER.info("接口文档:{}", address + "doc.html");
}
}
启动效果:
示例:CommandLineRunner
TODO 待补充