使用Spring Boot Initializr创建Eureka Server时构建失败:EventBus异常
我经常处理这类Spring Cloud Eureka的启动问题,你遇到的这个java.lang.IllegalStateException: Failed to load ApplicationContext嵌套UnsatisfiedDependencyException的异常,大概率是版本不兼容、配置错误或者注解用错导致的,给你几个针对性的解决办法:
检查Spring Boot与Spring Cloud的版本兼容性
这是最常见的诱因!不同版本的Spring Boot对应固定版本的Spring Cloud,比如Spring Boot 2.7.x要搭配Spring Cloud 2021.0.x(代号Jubilee),Spring Boot 3.x则对应Spring Cloud 2022.0.x(代号Kilburn)。版本不匹配会直接导致依赖注入失败。
你可以在pom.xml(Maven)里通过依赖管理锁定正确版本:<dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.5</version> <!-- 适配Spring Boot 2.7.x --> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Gradle用户则可以在
build.gradle里配置:implementation platform('org.springframework.cloud:spring-cloud-dependencies:2021.0.5')确认启动类的注解正确
Eureka Server的启动类必须标注@EnableEurekaServer,千万不要误加客户端用的@EnableEurekaClient,示例代码:@SpringBootApplication @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }修正Eureka Server的核心配置
默认情况下,Eureka Server会尝试把自己注册到注册中心,这会引发循环依赖问题。你需要在application.yml或application.properties里禁用这个行为:server: port: 8761 # Eureka默认端口 eureka: client: register-with-eureka: false # 禁止注册自己 fetch-registry: false # 禁止拉取服务列表如果你用properties格式:
server.port=8761 eureka.client.register-with-eureka=false eureka.client.fetch-registry=false清理并重新构建依赖
本地Maven/Gradle仓库的依赖文件损坏也可能导致这类异常,执行以下命令清理缓存并重新构建:
Maven用户:mvn clean install -UGradle用户:
gradle clean build --refresh-dependencies排除冲突的自动配置类
如果以上方法都无效,可能是自动配置类冲突导致的。你可以在启动类上排除Eureka客户端的自动配置:@SpringBootApplication(exclude = {EurekaClientAutoConfiguration.class}) @EnableEurekaServer public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } }
内容的提问来源于stack exchange,提问作者Prakash

