Spring Boot

Spring Boot

August 10, 2020
Spring

Spring Boot 提供了两个接口 CommandLineRunnerApplicationRunner,用以当 Spring Boot 应用程序完全启动之前运行指定的代码。

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

将参数封装为一个对象,可以调用 getOptionNames()getOptionValues()getSourceArgs() 等便捷的方法。

@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());
    }

}

排序

你可以注册任意多的 Runners,可以使用 @Order 注解来声明它们运行的顺序。

参考