You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中CommandLineRunner未执行问题求助

问题分析与解决方案

你的CommandLineRunnerTest类未被Spring Boot容器管理,因此启动时不会触发它的run方法,导致控制台看不到预期输出。

解决方法

方法一:添加组件注解

在CommandLineRunnerTest类上添加@Component注解,让Spring自动扫描并将其纳入容器:

package com.caido.frameworktest;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CommandLineRunnerTest implements CommandLineRunner {
    @Override
    public void run(String... strings) throws Exception {
        System.err.println("Start CommandLineRunner");
    }
}

方法二:手动注册Bean

若不想使用@Component,可在启动类中通过@Bean注解手动注册该CommandLineRunner:

package com.caido.frameworktest;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class FrameworktestApplication  {
    public static void main(String[] args) {
        System.out.println("Start run");
        SpringApplication.run(FrameworktestApplication.class, args);
    }

    @Bean
    public CommandLineRunner commandLineRunnerTest() {
        return new CommandLineRunnerTest();
    }
}

验证修改

重新启动应用后,你会在控制台Started FrameworktestApplication...日志之前看到Start CommandLineRunner的输出。

内容的提问来源于stack exchange,提问作者Victorqedu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 00:10:30