zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

2023-06-13 09:13:27 时间

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

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

CommandLineRunner

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

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

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

@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