Java中的循环依赖分两种:
构造器的循环依赖:就是在构造器中有属性循环依赖,如下所示的两个类就属于构造器循环依赖
@Service public class Student { @Autowired private Teacher teacher; public Student (Teacher teacher) { System.out.println("Student init1:" + teacher); } public void learn () { System.out.println("Student learn"); } } @Service public class Teacher { @Autowired private Student student; public Teacher (Student student) { System.out.println("Teacher init1:" + student); } public void teach () { System.out.println("teach:"); student.learn(); } }
这两个类都是定义了一个有参构造方法,所以Spring实例化的时候只能选取该构造方法了,这就意味着实例化的时候会尝试进行依赖注入。
这种循环依赖没有什么解决办法,因为JVM虚拟机在对类进行实例化的时候,需先实例化构造器的参数,而由于循环引用这个参数无法提前实例化,故只能抛出错误。
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException....
属性的循环依赖:就是A对象依赖了B对象,B对象依赖了A对象。
@Service public class Teacher { @Autowired private Student student; public Teacher () { System.out.println("Teacher init1:" + student); } public void teach () { System.out.println("teach:"); student.learn(); } } @Service public class Student { @Autowired private Teacher teacher; public Student () { System.out.println("Student init:" + teacher); } public void learn () { System.out.println("Student learn"); } }
两个类都只有默认的无参构造,所以实例化的时候不会主动进行依赖注入,只能按照@Autowired注解去注入属性了。 @Autowired注解注入也就相当于是setter注入了,这是即使发生了循环依赖,Spring也是可以解决的。
标签:依赖,Spring,System,public,循环,Student,println,Teacher,out From: https://www.cnblogs.com/nxjblog/p/17904358.html