Spring通過@Lazy解決構(gòu)造方法形式的循環(huán)依賴問題
更新時間:2023年10月06日 09:32:56 作者:amadeus_liu2
這篇文章主要給大家介紹了Spring如何通過@Lazy解決構(gòu)造方法形式的循環(huán)依賴問題,文中有詳細的代碼示例,對大家的學(xué)習(xí)活工作有一定的幫助,具有一定的參考價值,需要的朋友可以參考下
一、定義2個循環(huán)依賴的類
package cn.edu.tju.domain2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
public class A {
private final B b;
public B getB() {
return b;
}
@Lazy
public A(B b){
this.b = b;
//System.out.println(b);
}
}package cn.edu.tju.domain2;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
public class B {
private final A a;
public A getA() {
return a;
}
@Lazy
public B(A a){
this.a =a;
//System.out.println(a);
}
}二、定義配置文件(spring09.xml):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="cn.edu.tju.domain2"/>
</beans>三、定義測試類:
package cn.edu.tju;
import cn.edu.tju.domain.Husband;
import cn.edu.tju.domain2.A;
import cn.edu.tju.domain2.B;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.SQLException;
public class Test09 {
public static void main(String[] args) throws Exception {
ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("spring09.xml");
A a = ctx.getBean("a", A.class);
B b = ctx.getBean("b", B.class);
System.out.println(a.getClass().getName());
System.out.println(a.getB().getA() == a);
System.out.println(a.getB().getClass().getName());
System.out.println(b.getA().getClass().getName());
}
}四、執(zhí)行結(jié)果:

以上就是Spring通過@Lazy解決構(gòu)造方法形式的循環(huán)依賴問題的詳細內(nèi)容,更多關(guān)于Spring @Lazy解決循環(huán)依賴的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
SpringBoot+Apache tika實現(xiàn)文檔內(nèi)容解析的示例詳解
Apache tika是Apache開源的一個文檔解析工具,本文主要為大家介紹了如何在springboot中引入tika的方式解析文檔,感興趣的小伙伴可以了解一下2023-07-07
使用fastjson中的JSONPath處理json數(shù)據(jù)的方法
這篇文章主要介紹了使用fastjson中的JSONPath處理json數(shù)據(jù)的方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
Java?Maven構(gòu)建工具中mvnd和Gradle誰更快
這篇文章主要介紹了Java?Maven構(gòu)建工具中mvnd和Gradle誰更快,mvnd?是?Maven?Daemon?的縮寫?,翻譯成中文就是?Maven?守護進程,下文更多相關(guān)資料,需要的小伙伴可以參考一下2022-05-05

