SpringBoot启动后执行(回调/钩子)(CommandLineRunner与ApplicationRunner)

2022-06-22 14:39:47
  • 需求

    我们需要在项目启动完成后做一些操作,如:项目启动后打印访问地址、加载一些数据、获取第三方接口的Token、Tiket等等(题外话:获取token这些操作及初始化其实也可以在配置类@PostConstruct注解方法上执行)

    SpringBoot 提供了CommandLineRunner和ApplicationRunner 这两个接口实现这些需求,SpringBoot在启动后会在容器里取这两个接口的实例,如果有就调用实例的run方法;

@Configuration
@Slf4j
public class ApplicationConfig implements CommandLineRunner {

    @Value("${server.servlet.context-path}")
    private String path;

    @Value("${server.port}")
    private String port;

    @Override
    public void run(String... args) {
        log.info("Application Started At http://localhost:" + port + path);
    }
}
  • 了解

    先看一些这两个接口

    CommandLineRunner

package org.springframework.boot;

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

ApplicationRunner

package org.springframework.boot;

@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

可以看到这两个接口都有一个run方法:他们的相同点和不同点都在这个方法上。

  •   相同点:都会在启动后执行run方法,参数内容来源都是启动参数,即SpringBoot启动类main方法的参数String[] args
    public static void main(String[] args)
  •   不同点:参数不同 CommandLineRunner 的run方法参数是String[] ,ApplicationRunner的run方法参数是ApplicationArguments

  看一下ApplicationArguments这个类

package org.springframework.boot;

import java.util.List;
import java.util.Set;

public interface ApplicationArguments {
    String[] getSourceArgs();

    Set<String> getOptionNames();

    boolean containsOption(String name);

    List<String> getOptionValues(String name);

    List<String> getNonOptionArgs();
}

    ApplicationArguments类是对启动参数String[] args的简单的封装,可以执行根据参数名取值等等操作

  • 用法

     我们把这两个接口的实现类注册到Spring容器即可

在配置类注册

@Bean
public ApplicationRunner  applicationRunner(){
    return args -> log.info("ApplicationRunner实现");
}

@Bean
public CommandLineRunner commandLineRunner(){
    return  args -> log.info("CommandLineRunner实现");
}

    上面是匿名内部类的 Lambda实现等同于

@Bean
public ApplicationRunner applicationRunner(){
    return new ApplicationRunner() {
        @Override
	public void run(ApplicationArguments args) throws Exception {
	    log.info("ApplicationRunner实现");
	}
    };
}
@Bean
public CommandLineRunner commandLineRunner(){
    return  new CommandLineRunner() {
	@Override
	public void run(String... args) throws Exception {
	    log.info("CommandLineRunner实现");
	}
    };
}

也可编写接口实现类,并在类上添加注解 @Component

@Component
@Slf4j
public class ApplicationConfig implements CommandLineRunner {

	@Override
	public void run(String... args) {
		log.info("CommandLineRunner实现");
	}
}
  • 作者:轩墨宝宝
  • 原文链接:https://blog.csdn.net/xuanmobaobao/article/details/89015608
    更新时间:2022-06-22 14:39:47