Spring Boot2.6.0新特性之默認禁止循環引用

前言

如下代碼,ComponentA類註入ComponentB類,ComponentB類註入ComponentA類,就會發生循環依賴的問題,在2.6.0之前,spring會自動處理循環依賴的問題

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
 
@Service
public class ComponentA {
 
    @Resource
    private ComponentB componentB;
 
}
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
 
@Service
public class ComponentB {
 
    @Resource
    private ComponentA componentA;
 
}

現在,2.6.0 這個版本已經默認禁止 Bean 之間的循環引用,如果存在循環引用就會啟動失敗報錯:

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

┌─────┐
|  componentA
↑     ↓
|  componentB
└─────┘

Action:

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.

處理方案一:

 整改業務,清理掉所有存在循環引用的 Bean

處理方案二:

spring:
  main:
    allow-circular-references: true

處理方案三:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class SpringDemoApplication {
 
    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(SpringDemoApplication.class);
        application.setAllowCircularReferences(Boolean.TRUE);
        application.run(args);
    }
}

總結

到此這篇關於Spring Boot2.6.0新特性之默認禁止循環引用的文章就介紹到這瞭,更多相關SpringBoot2.6.0默認禁止循環引用內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: