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 using references to other services.
At the moment, people are instantiating needed services inside the constructor.
But now, I have trouble because service A needs service B and service B needs service A so a call to either constructor results in stack overflow …
Example (pseudo-code) :
//Constructor of OrderService
public OrderService() {
orderDAO = DAOFactory.getDAOFactory().getOrderDAO();
itemService = new ItemService();
}
//Constructor of ItemService
public ItemService() {
itemDAO = DAOFactory.getDAOFactory().getItemDAO();
orderService = new OrderService();
}
How would you solve this ? using singleton pattern ?
Thanks
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: