一、介绍
1、背景
@Autowired
注解在 Spring 框架中用于自动注入依赖关系。它常常被用来将一个类的实例自动注入到另一个类中,减少了手动配置 Bean 的复杂性。然而,当我们在类之间建立循环依赖关系时,@Autowired
注解可能会引起循环依赖问题,这种依赖关系会导致 Spring 无法在启动时正确初始化这些 Bean,因为每个 Bean 都在等待对方完成初始化,形成了死循环。
2、示例
CICD失败。如:
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private RoleService roleService;
@Override
public String testUser() {
String msg = "这是user";
msg = roleService.testRole(msg);
System.out.println(msg);
return msg;
}
@Override
public String check(String msg) {
msg += ":这是user最后check的";
return msg;
}
}
@Service("roleService")
public class RoleServiceImpl implements RoleService {
@Autowired
MenuService menuService;
@Override
public String testRole(String msg) {
msg += ":这是role";
return menuService.testMenu(msg);
}
}
@Service("menuService")
public class MenuServiceImpl implements MenuService {
@Autowired
private UserService userService;
@Override
public String testMenu(String msg) {
msg += ":这是Menu";
return userService.check(msg);
}
}
启动报错:
The dependencies of some of the beans in the application context form a cycle:
┌─────┐
| menuService (field private org.example.service.UserService org.example.service.impl.MenuServiceImpl.userService)
↑ ↓
| userService (field private org.example.service.RoleService org.example.service.impl.UserServiceImpl.roleService)
↑ ↓
| roleService (field org.example.service.MenuService org.example.service.impl.RoleServiceImpl.menuService)
└─────┘
Action:
Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.
3、根本原因
二、解决方法
1、在依赖链上使用@Lazy
@Lazy注解在Spring框架中用于声明一个bean的懒加载行为。当一个bean被标记为@Lazy时,它不会在容器启动时立即初始化,而是在第一次真正需要使用这个bean的时候才进行实例化。这个注解可以用在类或接口、方法上、字段上等。
package org.springframework.context.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Lazy {
boolean value() default true;
}
简单粗暴,但是不太推荐,后面新的业务逻辑会产生新的依赖链,依然可能出现相同的问题。
如我加在UserServiceImpl 引用的地方加上@Lazy注解:
@Lazy
@Autowired
private RoleService roleService;
可以正常启动。验证功能也正常:
@SpringBootTest(classes = {Main.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@RunWith(SpringRunner.class)
public class MyTest {
@Autowired
private UserService userService;
@Test
public void testUserString(){
String msg = userService.testUser();
System.out.println("结果:"+msg);
}
}
这是user:这是role:这是Menu:这是user最后check的
结果:这是user:这是role:这是Menu:这是user最后check的
2、Setter 注入或字段注入
不能使用构造器注入,而是使用setter或field注入,本质上是让spring帮忙解决循环依赖。适用于后续新接口实现不多的情况。
Spring 通过 Setter 方法或直接注入字段的方式来设置 Bean 的依赖。字段注入和 Setter 注入能够部分解决循环依赖问题,因为 Spring 会先实例化 Bean,然后通过反射调用 setter 方法注入依赖。在这种方式下,Spring 采用了 三级缓存(一级缓存:正常的 Bean 实例,二级缓存:正在创建中的 Bean 实例,三级缓存:正在依赖注入中的 Bean 实例)来处理循环依赖。
- 当 Spring 实例化一个 Bean(例如 A)时,如果它发现 A 需要依赖 B,那么 Spring 会创建 B,但不会马上注入 B 的依赖,而是暂时保存 B 的实例(在二级缓存中)。
- 然后 Spring 会继续创建 A 的依赖项,在这个过程中可能会涉及到 B 依赖 A 的情况。
- 最后,Spring 会把创建好的 A 和 B 都注入完成,依赖关系得到解决。
3、把构造器注入抽到一个新的类
保证依赖链上的类没有构造器注入,本质上也是让spring帮忙解决循环依赖。适用于后续会有新接口的情况,有新接口实现时不再需要额外修改。
4、重构业务逻辑
最优解是 重构代码,使得 Bean 之间的依赖关系更加清晰和松耦合。
三、开发建议
1、不要使用@async
spring 可以规避掉大多数的循环依赖,但是我们发现@async 注解使用会导致 这种机制失效
2、避免使用构造器注入
会导致spring自带的循环解决方案失效。如
public XxxService(@Qualifier("userMapper") UserMapper userMapper) {
this.userMapper= userMapper;
}