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
相关产品推荐
相关产品推荐

