Spring 默认是支持循环依赖(并且可以关闭)的,但是必须满足两个条件

  • 必须基于 setter 方法注入
  • 互斥引用的双方**不能都是 prototype 的 ```java @Service public class OrderService { @Autowired private UserService userService; public OrderService() {
    1. 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();

  1. System.out.println(ac.getBean(UserService.class));
  2. }

}

// 打印结果 UserService Constructor OrderService Constructor org.wesoft.spring.cycle.bean.UserService@3224f60b

  1. <a name="wIBvn"></a>
  2. ### 关闭循环依赖
  3. ```java
  4. public class App {
  5. public static void main(String[] args) {
  6. AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext();
  7. ac.register(AppConfig.class);
  8. // 关闭循环依赖
  9. DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) ac.getBeanFactory();
  10. beanFactory.setAllowCircularReferences(false);
  11. ac.refresh();
  12. System.out.println(ac.getBean(UserService.class));
  13. }
  14. }

循环依赖流程图

一直不太想写循环依赖逻辑,因为牵扯的知识点非常非常多,并不是网上很多说循环依赖的那么简单的几百个字,画张图吧,先走黑色线,再走蓝色线,再走橘黄色线,再走黄色线,再走墨兰色线

Spring 循环依赖.png