Spring循环依赖

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Spring循环依赖

IT利刃出鞘   2022-09-27 我要评论

简介

说明

本文用实例来介绍@Autowired解决循环依赖的原理。@Autowired是通过三级缓存来解决循环依赖的。 

除了@Autoired,还有其他方案来解决循环依赖的,见:Spring循环依赖的解决方案详解

概述

@Autowired进行属性注入可以解决循环依赖。原理是:Spring控制了bean的生命周期,先实例化bean,后注入bean的属性。Spring中记录了正在创建中的bean(已经实例化但还没初始化完毕的bean),所以可以在注入属性时,从记录的bean中取依赖的对象。

相对而言,单纯使用构造器注入就无法解决循环依赖。因为,在构造时就需要传入依赖的对象,导致无法实例化。(注意:构造器注入可以使用@Lazy解决循环依赖,在实例化时,传入代理对象,真正使用时才会生成真正的对象)

循环依赖实例

代码

package com.example.tmp;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class A {
    @Autowired
    private B b;
 
    private String name = "Tony";
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getTest() {
        return b.getAge().toString() + name;
    }
}
package com.example.tmp;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
 
@Component
public class B {
    @Autowired
    private A a;
 
    private Integer age = 20;
 
    public Integer getAge() {
        return age;
    }
 
    public void setAge(Integer age) {
        this.age = age;
    }
}
package com.example.controller;
 
import com.example.tmp.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
    @Autowired
    private A a;
 
    @GetMapping("/test1")
    public String test1() {
        return a.getTest();
    }
}

测试

1.启动不报错。

2.postman访问:http://localhost:8080/test1

后端结果:不报错

postman结果: 20Tony

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们