前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot扩展点 项目启动后立即执行

SpringBoot扩展点 项目启动后立即执行

作者头像
兜兜毛毛
发布2022-09-28 13:18:23
9250
发布2022-09-28 13:18:23
举报
文章被收录于专栏:兜兜毛毛兜兜毛毛

在平时开发时可能要实现在项目启动后执行的一些功能,此时可以使用SpringBoot提供的这个接口。

SpringBoot中有两个接口可以实现CommandLineRunner 或 ApplicationRunner

CommandLineRunner

该接口只有一个run(String... args)方法。

触发时机为整个项目启动完毕后,自动执行。如果有多个CommandLineRunner,可以使用@Order来进行排序。

扩展例子(打印web与swagger地址):

代码语言:javascript
复制
@Slf4j
@Component
public class ProjectInfoPrint implements CommandLineRunner {

    private final ApplicationContext applicationContext;

    public ProjectInfoPrint(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void run(String... args) throws Exception {
        Environment env = applicationContext.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String appName = env.getProperty("spring.application.name");
        log.info("\n----------------------------------------------------------\n" +
            "Application " + appName + " is running! Access URLs:\n\t" +
            "Local: \t\thttp://localhost:" + port + "/\n\t" +
            "External: \thttp://" + ip + ":" + port + "/\n\t" +
            "swagger-ui: http://" + ip + ":" + port + "/swagger-ui.html\n\t" +
            "swagger-docs: http://" + ip + ":" + port + "/doc.html\n\t" +
            "\n----------------------------------------------------------");
    }
}

输出效果:

ApplicationRunner

该接口也只有一个run(ApplicationArguments args)方法,可以获得更多参数相关信息。

使用上与CommandLineRunner基本没什么区别,但这两个接口有优先顺序。

SpringApplication.callRunners

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-09-07,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CommandLineRunner
  • ApplicationRunner
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档