在开发过程中,会不可避免的遇到Bean之间循环依赖的,所谓循环依赖,就是两个或者两个以上的Bean互相持有对方,这样在程序运行调用中,会出现这种循环依赖的现象,假设两个Bean,当程序调用Bean A时,Bean A中依赖Bean B,在BeanA中调用Bean B时,Bean B中又依赖了BeanA这样就形成了循环依赖,如下图:
先从一个小例子来说明,使用spring框架如果出现循环依赖会正常运行吗?下例是在spring BOOt的基础构建的,
代码结构如下:
程序访问入口是HelloController,他里面调用了HelloService1:
package com.pig.employee.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.pig.employee.service1.HelloService1;
@RestController
public class HelloController {
@Autowired
HelloService1 helloService1;
@RequestMapping("/hello")
public String sayHello() {
return helloService1.say1();
}
}
看一下HelloService1对应的实现类:
package com.pig.employee.service1.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pig.employee.service1.HelloService1;
import com.pig.employee.service2.HelloService2;
@Service("helloService1")
public class HelloService1Impl implements HelloService1 {
@Autowired
private HelloService2 helloService2;
@Override
public String say1() {
System.out.println(helloService2.toString());
return helloService2.say2();
}
}
实现类中依赖了HelloService2,再来看一下HelloService2的实现类:
package com.pig.employee.service2.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.pig.employee.service1.HelloService1;
import com.pig.employee.service2.HelloService2;
@Service("helloService2")
public class HelloService2Impl implements HelloService2 {
@Autowired
private HelloService1 helloService1;
@Override
public String say2() {
System.out.println(helloService1.toString());
return "helloService2 say hello";
}
}
HelloService2的实现类中又依赖了HelloService1,这样就形成了循环依赖,依托于Spring框架,这样的循环依赖能运行成功吗?废话不多说,直接运行不就出答案了,启动EmployeeApplication: