spring Cloud Alibaba 中優化多模塊代碼結構:將公共組件集中到 Common 模塊
在基于 spring cloud Alibaba (2021.0.1) 和 spring boot (2.6.4) 的微服務項目中,模塊化設計至關重要。本文探討如何有效地將多個業務模塊 (例如 merchant 和 supply 模塊) 的 Entity、Mapper 和 Service 層代碼集中到一個公共模塊 (common 模塊) 中,從而避免代碼冗余,提高代碼可維護性和復用性。
項目結構
假設項目結構如下:
- common 模塊: 包含 model (Entity)、mapper、service、impl、數據庫連接配置、統一異常處理、redis json 數據格式化、統一響應結果封裝、Swagger 集成、mybatis-Plus 配置、CORS 跨域配置等公共組件。
- merchant 模塊: 商戶端微服務,主要包含 Controller 層,對外提供 API 接口。
- supply 模塊: 供貨商端微服務,同樣主要包含 Controller 層,對外提供 API 接口。
問題及解決方案
在將公共組件集中到 common 模塊后,啟動 merchant 或 supply 模塊可能會遇到類似 org.springframework.beans.factory.BeanCreationException 的錯誤,提示 RequestMappingHandlerAdapter 或其他 Bean 初始化失敗。這通常是因為 Spring Boot 無法正確掃描到 common 模塊中的組件。
解決方法:
-
精確的包掃描配置: 在每個業務模塊 (例如 merchant 和 supply) 的啟動類中,使用 @SpringBootApplication 注解的 scanBasePackages 屬性,明確指定需要掃描的包路徑,確保包含 common 模塊的包路徑。例如:
@SpringBootApplication(scanBasePackages = {"com.quanneng", "com.quanneng.common"}) // 確保包含common模塊的包路徑 @MapperScan("com.quanneng.common.mapper") // 掃描common模塊下的Mapper接口 public class MerchantApiApplication { // ... }
注意: com.quanneng 替換為你的項目根包名,com.quanneng.common 為 common 模塊的包路徑。 @MapperScan 注解用于顯式掃描 common 模塊下的 Mapper 接口。
-
避免重復配置: 確保在 common 模塊中已經正確配置了數據庫連接、MyBatis-Plus、Swagger 等公共組件,并在業務模塊中避免重復配置這些組件。 例如,只在 common 模塊中配置 DataSource,業務模塊不再需要配置。
-
考慮創建 Spring Boot Starter: 為了更優雅地管理和復用 common 模塊,建議將其打包成一個 Spring Boot Starter。這樣,其他模塊只需要在 pom.xml 中添加依賴即可使用 common 模塊中的組件,無需手動配置包掃描路徑,也降低了出錯的可能性。
-
統一異常處理: 項目中應該只有一個統一的異常處理機制,避免在多個模塊中重復定義異常處理器。
通過以上步驟,可以有效地解決 BeanCreationException 錯誤,并實現 common 模塊中公共組件的復用,從而提高代碼質量和開發效率。 記住要仔細檢查包名和路徑的正確性,確保 Spring Boot 能正確掃描到 common 模塊中的所有組件。