改造过程中遇到的问题总结

当然,笔者在商品微服务改造过程中也遇到了几个小问题,在这里分享给各位读者,读者在实战时可以参考。

问题1:循环依赖

编码完成后,尝试启动项目。商品微服务无法启动,控制台报出了如下异常信息:

image 2025 04 23 14 13 59 286

日志中提示的信息足够清晰。在启动过程中发现了循环依赖的问题,从而导致项目无法启动。

以上就是问题的描述:项目无法启动,原因为循环依赖。

笔者想:明明是同样的代码,在单体项目中是正常的,到了微服务架构下怎么就出现问题了呢?

接下来尝试解决这个问题。其实,这个错误与 “单体/微服务” 无关,主要是 Spring Boot 自 2.6 版本开始就禁用了循环依赖,下面是 Spring Boot 2.6.0 版本发布时的说明:

Circular References Prohibited by Default
Circular references between beans are now prohibited by default. If your
application fails to start due to a BeanCurrentlyInCreationException you are
strongly encouraged to update your configuration to break the dependency cycle.
If you are unable to do so, circular references can be allowed again by setting
spring.main.allow-circular-references to true, or using the new setter

methods on SpringApplication and SpringApplicationBuilder This will restore
2.5's behaviour and automatically attempt to break the dependency cycle.

也就是说,如果在单体项目 newbee-mall-api 中升级 Spring Boot2.6 或以上版本,也可能报这个错误。因此,要想解决该问题,只需要解决循环依赖或通过配置让 Spring Boot 不强制禁用循环依赖。

具体到编码层面,可以使用 @Lazy 注解延迟加载某个陷入循环依赖的类,或者通过修改 allow-circular-references 配置项让 Spring Boot 允许循环依赖。以上两种方式都可以解决这个问题,笔者选择的是暂时允许循环依赖。打开 application.properties 配置文件,添加如下配置项即可。

spring.main.allow-circular-references=true

问题2:缺少LoadBalancer依赖

缺少 LoadBalancer 依赖依然会导致商品微服务无法正常启动,调试过程中控制台报出了如下异常信息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ltd.user.cloud.newbee.openfeign.NewBeeCloudAdminUserServiceFeign': Unexpected exception during bean creation; nested exception is java.lang.IllegalStateException: No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalancer?
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.15.jar:5.3.15]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.15.jar:5.3.15]

出现这个问题的原因非常简单:未引入负载均衡器。虽然简单,但是在实战过程中遇到了几次,主要是笔者在开发时粗心导致的。

在对应模块的 pom.xml 文件中加入 LoadBalancer 依赖即可。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

好的,后台管理系统中的商品管理模块接口和商品分类管理模块接口就改造完成了。不过,商品微服务中的接口不止这些,后续在改造商城端功能的时候还会继续在该模块下编码。希望读者能够根据笔者提供的开发步骤顺利地完成本节的项目改造。