SpringBoot

SpringBoot,第1张

SpringBoot

文章目录
    • 前言
    • 正文
      • 示例:ApplicationRunner
      • 示例:CommandLineRunner

前言

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5688006.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存