Spring Runner

Spring 应用的生命周期

Runner

Spring Boot 为我们提供了两个接口,CommandLineRunner 与 ApplicationRunner,它们能够在应用启动之后执行部分业务逻辑。

CommandLineRunner

CommandLineRunner 能够允许我们访问到应用的启动参数:

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
  private static final Logger logger = LoggerFactory.getLogger(
    CommandLineAppStartupRunner.class
  );

  @Override
  public void run(String... args) throws Exception {
    logger.info(
      "Application started with command-line arguments: {} . \n To kill this application, press Ctrl + C.",
      Arrays.toString(args)
    );
  }
}

ApplicationRunner

ApplicationRunner 则是对启动参数进行了二次封装:

@Component
public class AppStartupRunner implements ApplicationRunner {
  private static final Logger logger = LoggerFactory.getLogger(
    AppStartupRunner.class
  );

  @Override
  public void run(ApplicationArguments args) throws Exception {
    logger.info(
      "Your application started with option names : {}",
      args.getOptionNames()
    );
  }
}
下一页