2017-10-11 61 views
0

我有3类,即X,Y和Z。 x调用y的函数调用z的方法,并立即在方法得到执行后,我必须调用x的函数。这反过来导致依赖注入时产生无限的循环依赖。如何在Java中消除循环依赖关系?

如何解决这个问题?任何方式呢?

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可以摆弄。

+0

显示确切的代码,让我们了解您的缺陷是。 –

+1

重新排列你的代码,以便你不再有循环依赖。具有循环依赖性是您设计中出现问题的迹象,并且您的类之间的耦合过于紧密。 – Jesper

+0

@OlivierGrégoire完成。 –

回答

0

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

private void A(){ 
    B()  
} 

private void B(){ 
    C(); 
} 

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

这个答案可以解决无限递归,但是这不是OP的问题是什么。 – DodgyCodeException

+0

@克里斯·菲利普斯我总是需要从功能C.有一个在我的要求没有条件d这样调用函数的。 –

+0

@DodgyCodeException这是真的。 –