SpringBoot_ApplicationRunner实现项目启动后执行代码

前言

有些项目场景,我们需要在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 待补充

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值