Springboot的service循环依赖

项目中Service经常使用lombok提供的注解@RequiredArgsConstructor或者@AllArgsConstructor来注入其他Service

注解 @RequiredArgsConstructor生成带有必需参数的构造函数。 必需的参数是最终字段和具有约束的字段,例如@NonNull 。@AllArgsConstructor则是全部 但是使用的时候可能会存在循环依赖的问题
┌─────┐
|  sysUserV2ServiceImpl defined in URL [jar:file:/home/starwiz/data/hyt/starwiz.jar!/BOOT-INF/classes!/com/starwiz/project/system/v2/service/impl/SysUserV2ServiceImpl.class]
↑     ↓
|  processServiceImpl (field com.starwiz.project.workflow.WorkflowUtil com.starwiz.project.workflow.service.impl.ProcessServiceImpl.workflowUtil)
↑     ↓
|  workflowUtil (field com.starwiz.project.system.service.SysTodoService com.starwiz.project.workflow.WorkflowUtil.sysTodoService)
↑     ↓
|  sysTodoService (field private com.starwiz.project.warning.service.EarlyWarningFarmerService com.starwiz.project.system.service.impl.SysTodoServiceImpl.earlyWarningFarmerService)
↑     ↓
|  earlyWarningFarmerService (field com.starwiz.project.workflow.service.WorkflowService com.starwiz.project.warning.service.impl.EarlyWarningFarmerServiceImpl.workflowService)
↑     ↓
|  workflowServiceImpl (field com.starwiz.project.system.v2.service.SysUserV2Service com.starwiz.project.workflow.service.impl.WorkflowServiceImpl.sysUserV2Service)
└─────┘
    方法1
@Autowired
@Lazy //懒加载
    方法2
// lombok的注解 
@AllArgsConstructor
    方法3 使用 setter/field 方法注入
private DepartmentService departmentSerivce;
@Autowired
public void setDepartmentSerivce(DepartmentService departmentService) {
          
   
    this.departmentService = departmentService;
}
    方法4 使用 @PostConstruct
@Service
public class UserService {
          
   
    @Autowired
    private DepartmentService departmentService;
    @PostConstruct
    public void init() {
          
   
        departmentService.setUserService(this);
    }
    public DepartmentService getDepartmentService() {
          
   
        return departmentService;
    }
}
    方法5 实现ApplicationContextAware and InitializingBean接口
@Service
public class UserService implements ApplicationContextAware, InitializingBean {
          
   
 
    private DepartmentService departmentService;
 
    private ApplicationContext context;
 
    public DepartmentService getDepartmentService() {
          
   
        return departmentService;
    }
 
    @Override
    public void afterPropertiesSet() throws Exception {
          
   
        circB = context.getBean(DepartmentService.class);
    }
 
    @Override
    public void setApplicationContext(final ApplicationContext ctx) throws BeansException {
          
   
        context = ctx;
    }
}
使用Mybatis Plus時,可以将依赖 Service 换成依赖 Mapper,因为 Mapper 中也有这些基础方法
经验分享 程序员 微信小程序 职场和发展