在Spring Cloud Alibaba中如何將業務模塊的Entity、Mapper和Service集中到Common模塊中?

在Spring Cloud Alibaba中如何將業務模塊的Entity、Mapper和Service集中到Common模塊中?

spring Cloud Alibaba 項目中的公共模塊最佳實踐:集中 Entity、Mapper 和 Service

本文探討如何在 spring cloud Alibaba (版本 2021.0.1) 和 spring boot (版本 2.6.4) 項目中,有效地將多個業務模塊(例如 merchant 和 supply 模塊)的 Entity、Mapper 和 Service 集中到一個公共的 common 模塊中。 文中將分析常見問題及解決方案,并提供最佳實踐建議。

問題背景:

一個典型的多模塊 Spring Cloud Alibaba 項目,可能會遇到將公共組件(Entity、Mapper、Service 等)集中到 common 模塊后,其他業務模塊啟動失敗的問題。例如,出現 org.springframework.beans.factory.BeanCreationException 錯誤,提示 RequestMappingHandlerAdapter 或其他 Bean 初始化失敗。 即使 Swagger2 配置已正確放置在 common 模塊中,并能在業務模塊的 Controller 中正常工作,啟動問題仍然可能存在。

無效嘗試:

一些常見的嘗試,例如在業務模塊的啟動類中使用 @SpringBootApplication(scanBasePackages = “com.quanneng”) 或 @ComponentScan({“com.*”}) 進行包掃描,往往無法解決問題,仍然可能導致依賴注入失敗(例如 MerchantService 和 MerchantMapper Bean 創建失敗)。

解決方案與最佳實踐:

問題根源在于 Spring Boot 的自動配置和組件掃描機制。 簡單的包掃描可能導致沖突或遺漏。 以下步驟提供更穩健的解決方案:

  1. 模塊化設計: 將 common 模塊設計為一個 Spring Boot Starter。這能顯著簡化依賴管理,避免復雜的包掃描配置,并確保 common 模塊的組件能被其他模塊正確識別和使用。

  2. Starter 模塊結構: Starter 模塊應該包含:

    • pom.xml: 定義依賴關系,包含必要的 Spring Boot Starter 和其他依賴。
    • Entity 包: 包含所有業務實體類。
    • Mapper 包: 包含所有 mybatis Mapper 接口
    • Service 包: 包含所有業務服務接口和實現類。
    • AutoConfiguration 類: 使用 @Configuration 和 @Enable… 注解,配置必要的 Bean,例如 MyBatis 的 SqlSessionFactory。
  3. 業務模塊配置: 在每個業務模塊(例如 merchant 模塊)的 pom.xml 中,添加對 common Starter 模塊的依賴。 業務模塊的啟動類無需進行額外的包掃描配置。

  4. 避免重復配置: 確保在整個項目中,像 MyBatis 的配置、全局異常處理等,只在一個地方進行配置,通常在 common 模塊的 AutoConfiguration 類中。

  5. 細粒度控制: 如果需要對特定組件進行更細粒度的控制,可以在業務模塊中創建配置類,并使用 @Import 注解導入 common 模塊中的特定配置類或 Bean。

總結:

將公共組件集中到一個 Spring Boot Starter 模塊中,是解決 Spring Cloud Alibaba 項目中模塊化 Entity、Mapper 和 Service 的最佳實踐。 這種方法能有效避免包掃描沖突,簡化依賴管理,并提高代碼的可維護性和可重用性。 通過這種方式,可以確保 common 模塊中的組件在其他業務模塊中能被正確地加載和使用,從而避免啟動失敗等問題。

? 版權聲明
THE END
喜歡就支持一下吧
點贊6 分享