栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 待补充

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/685962.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号