ClassB -> ClassA循環(huán)依賴-->2個或以..."/>
溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

測試一下25道Spring經(jīng)典面試題你會幾道?循環(huán)依賴面試詳解

發(fā)布時間:2020-06-02 19:26:33 來源:網(wǎng)絡(luò) 閱讀:470 作者:架構(gòu)師追風(fēng) 欄目:編程語言

前言

先看看什么是循環(huán)依賴
當(dāng)一個ClassA依賴于ClassB,然后ClassB又反過來依賴ClassA,這就形成了一個循環(huán)依賴:
ClassA -> ClassB -> ClassA
循環(huán)依賴-->2個或以上bean 互相持有對方,最終形成閉環(huán).
Spring中循環(huán)依賴的場景:
1、構(gòu)造器的循環(huán)依賴。(spring也無能為力)
2、setter循環(huán)依賴:
field屬性的循環(huán)依賴【setter方式 單例,默認(rèn)方式-->通過遞歸方法找出當(dāng)前Bean所依賴的Bean,然后提前緩存【會放入Cach中】起來。通過提前暴露 -->暴露一個exposedObject用于返回提前暴露的Bean?!?br/>Spring是先將Bean對象實(shí)例化【依賴無參構(gòu)造函數(shù)】--->再設(shè)置對象屬性的
Spring先用構(gòu)造器實(shí)例化Bean對象----->將實(shí)例化結(jié)束的對象放到一個Map中,并且Spring提供獲取這個未設(shè)置屬性的實(shí)例化對象的引用方法。結(jié)合我們的實(shí)例來看,,當(dāng)Spring實(shí)例化了A、B、C后,緊接著會去設(shè)置對象的屬性,此時A依賴B,就會去Map中取出存在里面的單例B對象,以此類推,不會出來循環(huán)的問題嘍。

下面說一下Spring是如果解決循環(huán)依賴的

第一種:構(gòu)造器參數(shù)循環(huán)依賴
Spring容器會將每一個正在創(chuàng)建的Bean 標(biāo)識符放在一個“當(dāng)前創(chuàng)建Bean池”中,Bean標(biāo)識符在創(chuàng)建過程中將一直保持在這個池中。
因此如果在創(chuàng)建Bean過程中發(fā)現(xiàn)自己已經(jīng)在“當(dāng)前創(chuàng)建Bean池”里時將拋出BeanCurrentlyInCreationException異常表示循環(huán)依賴;而對于創(chuàng)建完畢的Bean將從“當(dāng)前創(chuàng)建Bean池”中清除掉。
首先我們先初始化三個Bean。

public class StudentA {

    private StudentB studentB ;

    public void setStudentB(StudentB studentB) {
        this.studentB = studentB;
    }

    public StudentA() {
    }

    public StudentA(StudentB studentB) {
        this.studentB = studentB;
    }
}
public class StudentB {

    private StudentC studentC ;

    public void setStudentC(StudentC studentC) {
        this.studentC = studentC;
    }

    public StudentB() {
    }

    public StudentB(StudentC studentC) {
        this.studentC = studentC;
    }
}
public class StudentC {

    private StudentA studentA ;

    public void setStudentA(StudentA studentA) {
        this.studentA = studentA;
    }

    public StudentC() {
    }

    public StudentC(StudentA studentA) {
        this.studentA = studentA;
    }
}

OK,上面是很基本的3個類,,StudentA有參構(gòu)造是StudentB。StudentB的有參構(gòu)造是StudentC,StudentC的有參構(gòu)造是StudentA ,這樣就產(chǎn)生了一個循環(huán)依賴的情況,
我們都把這三個Bean交給Spring管理,并用有參構(gòu)造實(shí)例化。

<bean id="a" class="com.zfx.student.StudentA">
        <constructor-arg index="0" ref="b"></constructor-arg>
    </bean>
    <bean id="b" class="com.zfx.student.StudentB">
        <constructor-arg index="0" ref="c"></constructor-arg>
    </bean>
    <bean id="c" class="com.zfx.student.StudentC">
        <constructor-arg index="0" ref="a"></constructor-arg>
    </bean> 

下面是測試類:
public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
        //System.out.println(context.getBean("a", StudentA.class));
    }
}

執(zhí)行結(jié)果報錯信息為:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: 
    Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?

如果大家理解開頭那句話的話,這個報錯應(yīng)該不驚訝,Spring容器先創(chuàng)建單例StudentA,StudentA依賴StudentB,然后將A放在“當(dāng)前創(chuàng)建Bean池”中,此時創(chuàng)建StudentB,StudentB依賴StudentC ,然后將B放在“當(dāng)前創(chuàng)建Bean池”中,此時創(chuàng)建StudentC,StudentC又依賴StudentA, 但是,此時Student已經(jīng)在池中,所以會報錯,,因為在池中的Bean都是未初始化完的,所以會依賴錯誤 ,(初始化完的Bean會從池中移除)
第二種:setter方式單例,默認(rèn)方式
如果要說setter方式注入的話,我們最好先看一張Spring中Bean實(shí)例化的圖

如圖中前兩步驟得知:Spring是先將Bean對象實(shí)例化之后再設(shè)置對象屬性的

修改配置文件為set方式注入

<!--scope="singleton"(默認(rèn)就是單例方式)  -->
    <bean id="a" class="com.zfx.student.StudentA" scope="singleton">
        <property name="studentB" ref="b"></property>
    </bean>
    <bean id="b" class="com.zfx.student.StudentB" scope="singleton">
        <property name="studentC" ref="c"></property>
    </bean>
    <bean id="c" class="com.zfx.student.StudentC" scope="singleton">
        <property name="studentA" ref="a"></property>
    </bean>

下面是測試類:

public class Test {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
        System.out.println(context.getBean("a", StudentA.class));
    }
}

打印結(jié)果為:

`com.zfx.student.StudentA@1fbfd6`

為什么用set方式就不報錯了呢 ?
我們結(jié)合上面那張圖看,Spring先是用構(gòu)造實(shí)例化Bean對象 ,此時Spring會將這個實(shí)例化結(jié)束的對象放到一個Map中,并且Spring提供了獲取這個未設(shè)置屬性的實(shí)例化對象引用的方法。
結(jié)合我們的實(shí)例來看,,當(dāng)Spring實(shí)例化了StudentA、StudentB、StudentC后,緊接著會去設(shè)置對象的屬性,此時StudentA依賴StudentB,就會去Map中取出存在里面的單例StudentB對象,以此類推,不會出來循環(huán)的問題嘍、
下面是Spring源碼中的實(shí)現(xiàn)方法。以下的源碼在Spring的Bean包中的DefaultSingletonBeanRegistry.java類中

/* Cache of singleton objects: bean name --> bean instance(緩存單例實(shí)例化對象的Map集合) /
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(64);

/** Cache of singleton factories: bean name --> ObjectFactory(單例的工廠Bean緩存集合) */
private final Map<String, ObjectFactory> singletonFactories = new HashMap<String, ObjectFactory>(16);

/** Cache of early singleton objects: bean name --> bean instance(早期的單身對象緩存集合) */
private final Map<String, Object> earlySingletonObjects = new HashMap<String, Object>(16);

/** Set of registered singletons, containing the bean names in registration order(單例的實(shí)例化對象名稱集合) */
private final Set<String> registeredSingletons = new LinkedHashSet<String>(64);
/**
 * 添加單例實(shí)例
 * 解決循環(huán)引用的問題
 * Add the given singleton factory for building the specified singleton
 * if necessary.
 * <p>To be called for eager registration of singletons, e.g. to be able to
 * resolve circular references.
 * @param beanName the name of the bean
 * @param singletonFactory the factory for the singleton object
 */
protected void addSingletonFactory(String beanName, ObjectFactory singletonFactory) {
    Assert.notNull(singletonFactory, "Singleton factory must not be null");
    synchronized (this.singletonObjects) {
        if (!this.singletonObjects.containsKey(beanName)) {
            this.singletonFactories.put(beanName, singletonFactory);
            this.earlySingletonObjects.remove(beanName);
            this.registeredSingletons.add(beanName);
        }
    }
}

**第三種:setter方式原型,prototype**
修改配置文件為:

<bean id="a" class="com.zfx.student.StudentA" scope="prototype">
<property name="studentB" ref="b"></property>
</bean>
<bean id="b" class="com.zfx.student.StudentB" scope="prototype">
<property name="studentC" ref="c"></property>
</bean>
<bean id="c" class="com.zfx.student.StudentC" scope="prototype">
<property name="studentA" ref="a"></property>
</b
```ean>


scope="prototype" 意思是 每次請求都會創(chuàng)建一個實(shí)例對象。
兩者的區(qū)別是:有狀態(tài)的bean都使用Prototype作用域,無狀態(tài)的一般都使用singleton單例作用域。
測試用例:

public class Test {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("com/zfx/student/applicationContext.xml");
//此時必須要獲取Spring管理的實(shí)例,因為現(xiàn)在scope="prototype" 只有請求獲取的時候才會實(shí)例化對象
System.out.println(context.getBean("a", StudentA.class));
}
}


打印結(jié)果:

Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException:
Error creating bean with name 'a': Requested bean is currently in creation: Is there an unresolvable circular reference?



為什么原型模式就報錯了呢?
對于“prototype”作用域Bean,Spring容器無法完成依賴注入,因為“prototype”作用域的Bean,Spring容器不進(jìn)行緩存,因此無法提前暴露一個創(chuàng)建中的Bean。

# 大家可以再回過頭來看看以下Spring面試題,你自己能答對幾道呢?
1 、什么是 Spring  框架?Spring  框架有哪些主要模塊?
2 、使用 Spring  框架能帶來哪些好處?
3 、什么是控制反轉(zhuǎn)(IOC) ?什么是依賴注入?
4 、請解釋下 Spring  框架中的 IoC ?
5 、BeanFactory 和 和 ApplicationContext  有什么區(qū)別?
6 、Spring  有幾種配置方式?
7 、如何用基于 XML  配置的方式配置 Spring ?
8 、如何用基于 Java  配置的方式配置 Spring ?
9 、怎樣用注解的方式配置 Spring ?
10 、請解釋 Spring Bean  的生命周期?
11 、Spring Bean  的作用域之間有什么區(qū)別?
12 、什么是 Spring inner beans ?
13 、Spring  框架中的單例 Beans  是線程安全的么?
14 、請舉例說明如何在 Spring  中注入一個 Java Collection ?
15 、如何向 Spring Bean  中注入一個 Java.util.Properties 
16 、請解釋 Spring Bean  的自動裝配?
17 、請解釋自動裝配模式的區(qū)別?
18 、如何開啟基于注解的自動裝配?
19 、請舉例解釋@Required  注解?
20 、請舉例解釋@Autowired  注解?
21 、請舉例說明@Qualifier  注解?
22 、構(gòu)造方法注入和設(shè)值注入有什么區(qū)別?
23 、Spring  框架中有哪些不同類型的事件?
24 、FileSystemResource 和 和 ClassPathResource  有何區(qū)別?
25 、Spring  框架中都用到了哪些設(shè)計模式?

**歡迎大家一起交流,喜歡文章記得點(diǎn)個贊,感謝支持!**
向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI