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获取

Spring Boot 中,`CommandLineRunner` 是一种方便的方式来在应用程序启动时运行一些初始化任务,比如数据迁移、日志配置等。如果你想在 `run` 方法执行完后注入依赖的 Bean,通常不会直接在 `run` 方法内部注入,因为这会违背单例模式,可能导致并发问题。 然而,你可以通过以下几种方式间接实现: 1. **使用 @PostConstruct 注解**: 如果你想确保某个Bean在 `CommandLineRunner` 完成后立即执行,可以在该Bean上添加 `@PostConstruct` 注解,Spring会在所有 `CommandLineRunner` 执行完毕后再调用这个方法。 ```java @Component public class MyComponent { @Autowired private SomeDependency dependency; // 使用 @PostConstruct 注解的方法 @PostConstruct public void init() { // 这里可以使用已经注入的 dependency } // CommandLineRunner 的 run 方法 @Override public void run(String... args) throws Exception { // ... } } ``` 2. **使用 ApplicationRunner** 或者 **ApplicationArgumentsRunner** 替代 CommandLineRunner: 这些接口允许你在应用启动过程中执行更细粒度的任务,并且它们允许在每个命令行参数处理后或整个参数处理完成后注册回调方法。 ```java @Component public class MyApplicationRunner implements ApplicationRunner { @Autowired private SomeDependency dependency; @Override public void run(ApplicationArguments args) { // 在这里,args.getApplicationArguments() 可以获取参数 // 然后在合适的地方注入 dependency // ... } } ``` 3. **Spring Boot Actuator**: 如果是用于服务启动后的配置,可以考虑使用 Actuator 提供的工具如 HealthIndicator 或 MetricsEndpoint,它们会在启动后提供注册点。 重要的是,确保你的 Bean 配置为 Spring 容器管理,并且在整个生命周期内可用,而不是仅在特定的执行阶段。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值