Spring Boot在macOS ARM架构JAR运行时@ConditionalOnMissingBean异常问题
Spring Boot在macOS ARM下JAR运行时Bean注册异常问题
场景描述
应用通过DefaultConfig和LocalConfig两个配置类定义AppServiceResolver类型的Bean:
DefaultConfig中的Bean带有@ConditionalOnMissingBean(AppServiceResolver.class)注解,作为默认实现LocalConfig带有@Profile("local")注解,仅在激活local配置文件时生效,提供本地环境的Bean实现
预期行为:激活local配置文件时,仅LocalConfig中的Bean被注册。此逻辑在Windows/macOS IDE中运行正常,Windows下JAR运行也正常,但仅在macOS ARM芯片环境下运行打包后的JAR时,抛出BeanDefinitionOverrideException。
异常信息
*************************** APPLICATION FAILED TO START *************************** Description: The bean 'appServiceResolver', defined in class path resource [com/example/project/config/LocalConfig.class], could not be registered. A bean with that name has already been defined in class path resource [com/example/project/config/DefaultConfig.class] and overriding is disabled. Action: Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
相关代码
DefaultConfig.java
@Configuration public class DefaultConfig { @Bean @ConditionalOnMissingBean(AppServiceResolver.class) AppServiceResolver appServiceResolver() { return new DefaultServiceResolver(); } // Additional bean definitions... }
LocalConfig.java
@Configuration @Profile("local") public class LocalConfig { @Bean AppServiceResolver appServiceResolver(){ return new LocalServiceResolver(); } // Additional bean definitions under "local" profile... }
构建命令
./gradlew clean bootJar
环境信息
- Spring Boot版本:3.0.5
- Java版本:17.0.10
问题分析与无源码修改解决方案
该问题大概率与macOS ARM架构下JAR打包后的类路径扫描/加载顺序差异有关:不同环境下Spring Boot配置类的加载顺序可能变化,导致激活local profile时,DefaultConfig的Bean先完成注册,后续LocalConfig的Bean注册时触发覆盖异常。
无需修改Java源码的解决方案:
- 在
application-local.properties(或application-local.yml)中添加以下配置:
spring.main.allow-bean-definition-overriding=true
此配置仅在激活local profile时生效,允许LocalConfig中的appServiceResolver覆盖默认实现,既满足本地环境需求,又不会影响其他环境的运行逻辑。
内容的提问来源于stack exchange,提问作者loone96
相关产品推荐
相关产品推荐

