springboot启动事件CommandLineRunner使用
什么是CommandRunner
CommandRunner是springboot启动完成时会调用的一个runner 启动参数会传递到这个runner 我们能用来做一些初始化工作和缓存预热等工作
ApplicationRunner VS CommandRunner?
这两个Runner作用一样 只是得到的启动参数格式不一样 前者是一个Argument对象 后者是参数字符串数组 功能更强大
使用方法
编写一个Runner类实现CommandRunner接口 重写run方法 runner被调用时run方法会被执行 Runner类需要注册成一个组件被spring管理
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
private static final Logger log = LoggerFactory.getLogger(CommandLineRunnerImpl.class);
private Environment environment;
public CommandLineRunnerImpl(Environment environment) {
this.environment = environment;
}
@Override
public void run(String... args) throws Exception {
log.info("command line args: {}", Arrays.toString(args)); // [--spring.profiles.active=prod, --server.port=9091]
log.info("command line environment: {}", environment.getActiveProfiles()); // prod
log.info("command line environment: {}", environment.getProperty("server.port")); // 9091
}
}
修改启动的configuration 加入启动参数:
启动项目后 控制台输出:
除了从run方法参数获取还可以通过environment对象的getProperty获取