Spring 默认是支持循环依赖(并且可以关闭)的,但是必须满足两个条件
- 必须基于 setter 方法注入
- 互斥引用的双方**不能都是 prototype 的
```java
@Service
public class OrderService {
@Autowired
private UserService userService;
public OrderService() {
} }System.out.println("OrderService Constructor");
@Service public class UserService { @Autowired private OrderService orderService; public UserService() { System.out.println(“UserService Constructor”); } }
public class App { public static void main(String[] args) { AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(); ac.register(AppConfig.class); ac.refresh();
System.out.println(ac.getBean(UserService.class));
}
}
// 打印结果 UserService Constructor OrderService Constructor org.wesoft.spring.cycle.bean.UserService@3224f60b
<a name="wIBvn"></a>
### 关闭循环依赖
```java
public class App {
public static void main(String[] args) {
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
ac.register(AppConfig.class);
// 关闭循环依赖
DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ac.getBeanFactory();
beanFactory.setAllowCircularReferences(false);
ac.refresh();
System.out.println(ac.getBean(UserService.class));
}
}
循环依赖流程图
一直不太想写循环依赖逻辑,因为牵扯的知识点非常非常多,并不是网上很多说循环依赖的那么简单的几百个字,画张图吧,先走黑色线,再走蓝色线,再走橘黄色线,再走黄色线,再走墨兰色线