如何在Java中恢复循环依赖?

时间:2017-10-11 13:39:12

标签: java class circular-dependency circular-reference

我有3个类,即x,y和z。 x调用y的函数调用z的方法,并且在方法以相同的方法执行后立即调用x的函数。这反过来会导致依赖注入时无限循环依赖。

如何解决此问题?有什么办法吗?

EventService类(类X)

    private void callHandlers(ApplicationEvent event) {
            ChecklistEventHandler handler = new ChecklistEventHandler();
            handler.handle(event); // here class Y is getting called.
    }

    public void createEvent(String type, String key, String creator, Map<String, Object> data) {
        AccountInfo accountInfo = (AccountInfo) Http.Context.current().args.get(GtConstants.ACCOUNT_INFO);
        String eventData = JacksonUtil.toString(data);
        ApplicationEvent event = new ApplicationEvent(accountInfo.getSchemaName(), type, key, creator, eventData);
        repository.save(event);
        scheduleForProcessing(event,accountInfo);
    }

ChecklistEventHandler类(Y类)

 public void handle(ApplicationEvent event) {
    ChecklistCriteria checklistCriteria = new ChecklistCriteria();
    checklistCriteria.setEventType(event.getType());
    checklistCriteria.setArchived(false);
    taskManagementService.createChecklistInstancesAndTask(event, checklistCriteria); // here class Z is getting called.
 }

TaskManagementService类(Z类)

 public void createChecklistInstancesAndTask(ApplicationEvent event, ChecklistCriteria checklistCriteria) {
    List<Checklist> checkListCollection = getChecklistCollectionBasedOnEvent(checklistCriteria.getEventType(),
            checklistCriteria.getArchived(),
    LocalDate now = LocalDate.now();
    createChecklistInstancesAndTask(event, checkListCollection, now); 
      //here i am calling EventService class (class X)            eventService.createEvent(TaskConstants.EventType.COMPLETE_CHECKLIST_INSTANCE,
String.valueOf(checklistInstance.getId()),   TaskConstants.EventCreator.TASK_STATUS_UPDATOR, taskMap);
}

希望这可以解除你的疑虑。现在我如何在不替换X和Y类函数的情况下重新设计它。类z可以摆弄。

1 个答案:

答案 0 :(得分:0)

为了解决循环依赖关系,您需要定义终止条件。问问自己需要满足哪些条件才能使代码在除已定义的递归路径之外的路径上开始执行。所以

private void A(){ 
     B()    
}

private void B(){
     C();
}

private void C(){
     if(conditionD){
          D();
     }else{
          A();
     }
}