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

Spring Boot中两个CommandLineRunner类启动报错问题咨询

解决Spring Boot多CommandLineRunner启动类的冲突问题

嘿,这个场景我之前踩过坑!当你的项目里存在多个标注了@SpringBootApplication的类时,Spring Boot启动时确实会因为无法确定哪个是主入口类而报错。这里有几个实用的解决办法:

方法一:启动时指定主类

直接在java -jar命令里通过参数指定要启动的主类全限定名,有两种方式:

  • 使用--spring.main.main-class参数:
    java -jar your-project.jar --spring.main.main-class=com.xxxx.Application
    
  • 使用JVM系统属性-D:
    java -jar -Dspring.main.main-class=com.xxxx.ApplicationWorklfow your-project.jar
    

方法二:打包时配置默认主类

如果希望打包后的jar默认启动某个主类,可以在构建工具里配置:

Maven项目

在pom.xml的spring-boot-maven-plugin中指定mainClass:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <!-- 替换成你要默认启动的类的全限定名 -->
                <mainClass>com.xxxx.Application</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

Gradle项目

在build.gradle中配置springBoot的mainClass:

springBoot {
    mainClass = 'com.xxxx.ApplicationWorklfow'
}

方法三:优化代码结构(推荐)

其实Spring Boot项目的最佳实践是只保留一个@SpringBootApplication类作为启动入口。另一个实现CommandLineRunner的类只需要去掉@SpringBootApplication和@ComponentScan,添加普通的组件注解(比如@Component)即可。这样启动时Spring只会加载一个主入口类,而另一个CommandLineRunner会作为普通组件被容器管理,启动时照样会执行run()方法,从根源上避免冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:41:33