SpringBoot2.6.x默認禁用循環依賴后的應對策略


一、序言

SpringBoot 2.6.x不推薦使用循環依賴,這是一個好消息,SpringBoot從底層逐漸引導開發者書寫規范的代碼,同時也是個憂傷的消息,循環依賴的應用場景實在是太廣泛了。

如果從低版本升級到2.6.x,那么很大概率遇到的第一個問題便是循環依賴問題。

二、問題復原

1、代碼說明

下面風格的代碼比較普遍:兩個類都有調用對方方法的需求,因此很容易寫成循環引用。

@Service
public class TbDeptServiceImpl extends ServiceImpl<TbDeptMapper, TbDept> implements ITbDeptService {
    
    @Autowired
    private ITbStaffService staffService;
}

@Service
public class TbStaffServiceImpl extends ServiceImpl<TbStaffMapper, TbStaff> implements ITbStaffService {
    @Autowired
    private ITbDeptService deptService;
}
2、錯誤示例
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Despite circular references being allowed, the dependency cycle between beans could not be broken. Update your application to remove the dependency cycle.

三、問題解決

1、粗暴解決

最簡單的方式是在全局配置文件中允許循環引用存在,此屬性默認值為false,顯示聲明為true,可回避項目啟動時控制台循環引用異常。

spring:
  main:
    allow-circular-references: true
2、優雅解決

Spring官方默認禁止使用循環依賴,盡管留有可選配置,允許開發者繼續使用循環依賴。

Spring官方的初心是不希望開發者編寫循環依賴的代碼,也就是說未來的某個版本可能強制不得使用循環依賴,因此逐漸在新項目中消除循環依賴是不得不面對的問題。

使用方法的返回值獲取實例對象,替換通過成員變量注入實例對象。

@Service
public class TbDeptServiceImpl extends ServiceImpl<TbDeptMapper, TbDept> implements ITbDeptService {
    /**
     * 使用方法返回實例對象,替換成員變量注入
     * @return ITbStaffService
     */
    public ITbStaffService getStaffService(){
        return SpringUtils.getBean(ITbStaffService.class);
    }
}
@Service
public class TbStaffServiceImpl extends ServiceImpl<TbStaffMapper, TbStaff> implements ITbStaffService {
    /**
     * 使用方法返回實例對象,替換成員變量注入
     * @return ITbStaffService
     */
    public ITbDeptService getDeptService(){
        return SpringUtils.getBean(ITbDeptService.class);
    }
}

其中需要使用如下依賴,此依賴是筆者抽離出來的公共依賴,可跨項目使用。

<dependency>
    <groupId>xin.altitude.cms.common</groupId>
    <artifactId>ucode-cms-common</artifactId>
    <version>1.3.4</version>
</dependency>

如果找不到此依賴,很大可能是阿里雲Maven倉庫尚未同步,在項目中強制使用Maven中央倉庫即可。

<repositories>
    <repository>
        <id>public</id>
        <name>maven nexus</name>
        <url>https://repo1.maven.org/maven2/</url>
        <snapshots>
            <updatePolicy>always</updatePolicy>
        </snapshots>
    </repository>
</repositories>

四、小結

Spring生態作為廣泛使用的框架,儼然成為Java企業級應用主流標准,其微小的變化對整合生態帶來不可估量的影響。從跟隨者轉化為引導者,果斷禁止循環依賴問題,體現的是作為引導者的擔當。

循環引用使用習慣了,初步看起來代碼沒毛病,仔細想想是不合理的設計。循環依賴的直接表現是你中有我,我中有你,從對象的設計上令人費解。

最為開發者時刻關注底層框架的變動,將會在應用層收益。這里所說的底層框架是指JDK、Spring生態、Apache、知名大廠開源並廣泛被應用的框架,比如guava等。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM