Spring解决循环依赖问题的四种方法汇总

 更新时间:2024年07月21日 13:58:35   作者:jc0803kevin  
这篇文章主要介绍了Spring解决循环依赖问题的四种方法汇总,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧

Spring解决循环依赖问题的四种方法

  • @Lazy方式
  • 使用Setter/Field Injection
  • 使用@PostConstruct
  • 实现 ApplicationContextAware 和 InitializingBean

不管使用那种方式,最佳的还是通过调整代码结构,从根上设计从而达到避免。

定义两个相互依赖的 bean(通过构造函数注入)

package icu.kevin.springpart.circular.constructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyA {
    private CircularDependencyB circB;
    @Autowired
    public CircularDependencyA(CircularDependencyB circB) {
        this.circB = circB;
    }
}
package icu.kevin.springpart.circular.constructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyB {
    private CircularDependencyA circA;
    @Autowired
    public CircularDependencyB(CircularDependencyA circA) {
        this.circA = circA;
    }
}
package icu.kevin.springpart.circular.constructor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = { "icu.kevin.springpart.circular.constructor" })
public class TestConfig {
}

编写测试用例,测试是否存在循环依赖

package icu.kevin.springpart.circular.constructor;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class CircularDependencyIntegrationTest {
    // Error creating bean with name 'circularDependencyA': Requested bean is currently in creation: Is there an unresolvable circular reference?
    @Test
    public void givenCircularDependency_whenConstructorInjection_thenItFails() {
        // 测试可以为空,因为在上下文加载期间将检测到循环依赖关系
    }
}

@Lazy方式

@Lazy告诉 Spring 延迟初始化其中一个 bean。因此,它不会完全初始化 Bean,而是创建一个代理将其注入另一个 Bean。注入的 Bean 只有在第一次需要时才会完全创建。

@Lazy 注解是通过建立一个中间代理层,来破解循环依赖的。

package icu.kevin.springpart.circular.lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyA {
    private CircularDependencyB circB;
    @Autowired
    public CircularDependencyA(@Lazy CircularDependencyB circB) {
        this.circB = circB;
    }
}
package icu.kevin.springpart.circular.lazy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyB {
    private CircularDependencyA circA;
    @Autowired
    public CircularDependencyB(CircularDependencyA circA) {
        this.circA = circA;
    }
}
package icu.kevin.springpart.circular.lazy;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = { "icu.kevin.springpart.circular.lazy" })
public class TestConfig {
}
package icu.kevin.springpart.circular.lazy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class CircularDependencyIntegrationTest {
    // Error creating bean with name 'circularDependencyA': Requested bean is currently in creation: Is there an unresolvable circular reference?
    @Test
    public void givenCircularDependency_whenConstructorInjection_thenItFails() {
        // 测试可以为空,因为在上下文加载期间将检测到循环依赖关系
    }
}

启动可以看出,在上下文检查循环依赖是可以正常通过的

查看源码ContextAnnotationAutowireCandidateResolver#getLazyResolutionProxyIfNecessary首先会调用 isLazy 去判断一下是否需要延迟加载,
如果需要,则调用 buildLazyResolutionProxy 方法构建一个延迟加载的对象;

使用Setter/Field Injection

在setter注入的时候发生的依赖循环是可以被解决的,但只能解决单例情况的循环依赖。
对于setter注入造成的依赖是通过Spring容器提前暴露刚刚完成构造器但还没有进行注入的bean来完成的。通过提前暴露一个单例工厂让其他的bean可以引用到该Bean。

package icu.kevin.springpart.circular.setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyA {
    private CircularDependencyB circB;
    public CircularDependencyB getCircB() {
        return circB;
    }
    @Autowired
    public void setCircB(CircularDependencyB circB) {
        this.circB = circB;
    }
}
package icu.kevin.springpart.circular.setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyB {
    private CircularDependencyA circA;
    private String message = "Hi!";
    public CircularDependencyA getCircA() {
        return circA;
    }
    @Autowired
    public void setCircA(CircularDependencyA circA) {
        this.circA = circA;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}
package icu.kevin.springpart.circular.setter;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = { "icu.kevin.springpart.circular.setter" })
public class TestConfig {
}
package icu.kevin.springpart.circular.setter;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class CircularDependencyIntegrationTest {
    @Autowired
    private ApplicationContext context;
    @Test
    public void givenCircularDependency_whenConstructorInjection_thenItFails() {
        // Empty test; we just want the context to load
        CircularDependencyA circA = context.getBean(CircularDependencyA.class);
        Assert.assertEquals("Hi!", circA.getCircB().getMessage());
    }
}

使用@PostConstruct

package icu.kevin.springpart.circular.postConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
public class CircularDependencyA {
    @Autowired
    private CircularDependencyB circB;
    @PostConstruct
    public void init(){
        circB.setCircA(this);
    }
    public CircularDependencyB getCircB() {
        return circB;
    }
}
package icu.kevin.springpart.circular.postConstruct;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyB {
    private CircularDependencyA circA;
    private String message = "Hi!";
    public CircularDependencyA getCircA() {
        return circA;
    }
    public void setCircA(CircularDependencyA circA) {
        this.circA = circA;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}
package icu.kevin.springpart.circular.postConstruct;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = { "icu.kevin.springpart.circular.postConstruct" })
public class TestConfig {
}
package icu.kevin.springpart.circular.postConstruct;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class CircularDependencyIntegrationTest {
    @Autowired
    private ApplicationContext context;
    @Test
    public void givenCircularDependency_whenConstructorInjection_thenItFails() {
        //
        CircularDependencyA circA = context.getBean(CircularDependencyA.class);
        Assert.assertEquals("Hi!", circA.getCircB().getMessage());
    }
}

实现 ApplicationContextAware 和 InitializingBean

如果其中一个 Bean 实现了 ApplicationContextAware,则该 Bean 可以访问 Spring 上下文,并可以从那里提取另一个 Bean。

通过实现 InitializingBean,我们指示该 Bean 在设置完所有属性后必须执行一些操作。在这种情况下,我们要手动设置依赖项。

package icu.kevin.springpart.circular.initializingBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyA implements ApplicationContextAware, InitializingBean {
    private CircularDependencyB circB;
    private ApplicationContext context;
    public CircularDependencyB getCircB() {
        return circB;
    }
    @Override
    public void afterPropertiesSet() throws Exception {
        circB = context.getBean(CircularDependencyB.class);
    }
    @Override
    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
        context = ctx;
    }
}
package icu.kevin.springpart.circular.initializingBean;
import org.springframework.stereotype.Component;
@Component
public class CircularDependencyB {
    private CircularDependencyA circA;
    private String message = "Hi!";
    public CircularDependencyA getCircA() {
        return circA;
    }
    public void setCircA(CircularDependencyA circA) {
        this.circA = circA;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
}
package icu.kevin.springpart.circular.initializingBean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan(basePackages = { "icu.kevin.springpart.circular.initializingBean" })
public class TestConfig {
}
package icu.kevin.springpart.circular.initializingBean;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { TestConfig.class })
public class CircularDependencyIntegrationTest {
    @Autowired
    private ApplicationContext context;
    @Test
    public void givenCircularDependency_whenConstructorInjection_thenItFails() {
        // Empty test; we just want the context to load
        CircularDependencyA circA = context.getBean(CircularDependencyA.class);
        Assert.assertEquals("Hi!", circA.getCircB().getMessage());
    }
}

到此这篇关于Spring解决循环依赖问题的四种方法的文章就介绍到这了,更多相关Spring循环依赖内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java模拟实现QQ三方登录(单点登录2.0)

    Java模拟实现QQ三方登录(单点登录2.0)

    这篇文章主要为大家详细介绍了Java模拟实现QQ三方登录,单点登录2.0,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2020-06-06
  • Apache Commons fileUpload文件上传多个示例分享

    Apache Commons fileUpload文件上传多个示例分享

    这篇文章主要为大家分享了Apache Commons fileUpload文件上传4个示例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-10-10
  • Struts2学习笔记(6)-简单的数据校验

    Struts2学习笔记(6)-简单的数据校验

    这篇文章主要介绍Struts2中的数据校验,通过一个简单的例子来说明,希望能给大家做一个参考。
    2016-06-06
  • java 图片验证码的实现代码

    java 图片验证码的实现代码

    java 图片验证码的实现代码,需要的朋友可以参考一下
    2013-05-05
  • SpringBoot动态定时任务实现完整版

    SpringBoot动态定时任务实现完整版

    最近有幸要开发个动态定时任务,这里简单再梳理一下,下面这篇文章主要给大家介绍了关于SpringBoot动态定时任务实现的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2023-02-02
  • 详解SpringBoot可执行Jar包运行原理

    详解SpringBoot可执行Jar包运行原理

    SpringBoot有一个很方便的功能就是可以将应用打成可执行的Jar,那么大家有没想过这个Jar是怎么运行起来的呢,本篇博客就来介绍下 SpringBoot可执行Jar包的运行原理,需要的朋友可以参考下
    2023-05-05
  • 详解MyEclipse中搭建spring-boot+mybatis+freemarker框架

    详解MyEclipse中搭建spring-boot+mybatis+freemarker框架

    这篇文章主要介绍了详解MyEclipse中搭建spring-boot+mybatis+freemarker框架,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Maven中pom.xml文件报错的原因解决

    Maven中pom.xml文件报错的原因解决

    创建Maven项目的时候,如果你选择的Packaging为war,那么就会报错,本文主要介绍了Maven中pom.xml文件报错的原因解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2023-07-07
  • SpringData Repository Bean方法定义规范代码实例

    SpringData Repository Bean方法定义规范代码实例

    这篇文章主要介绍了SpringData Repository Bean方法定义规范代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • restTemplate超时处理的策略方案

    restTemplate超时处理的策略方案

    这篇文章主要为大家介绍了restTemplate超时处理的策略方案,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06

最新评论