Spring Boot
Spring Boot 提供了两个接口 CommandLineRunner
和 ApplicationRunner
,用以当 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
注解来声明它们运行的顺序。