Java circular references

前端 未结 4 1347
伪装坚强ぢ
伪装坚强ぢ 2021-01-21 02:01

In the project im working on, people wrote services class to access DAO. Almost every business object has it\'s own service which use it\'s own DAO. On some services, we are usi

4条回答
  •  猫巷女王i
    2021-01-21 02:46

    The Spring Framework solves this problem by using dependency injection. In short, what it does is to instantiate all the DAOs, and then set the dao-dependencies after instantiation, but before main business logic.

    If you have to do this manually, here's an example:

    /*
      OrderService
     */
    public OrderService ()
    {
         orderDAO = DAOFactory.getDAOFactory().getOrderDAO();
    }
    
    public setItemService (ItemService service)
    {
         itemService = service;
    }
    
    /*
      ItemService
     */
    public ItemService ()
    {
         itemDAO = DAOFactory.getDAOFactory().getItemDAO();
    }
    
    public setOrderService (OrderService service)
    {
         orderService = service;
    }
    
    /*
       Bring it together in some other class
     */
    ...
    // instantiate singletons
    orderService = new OrderService ();
    itemService = new ItemService ();
    
    // inject dependencies
    orderService.setItemService (itemService);
    itemService.setOrderService (orderService);
    

提交回复
热议问题