Dependency Injection to avoid circular dependencies
October 29, 2009
Posted by on
Dependencies injection saves the day again, this time in helping work around a circular dependency.
Often you have to work with legacy code that can not be changed easily. In my case I had a project called Gateway (containing a JSON Gateway) that depends on a project called Common. I needed an instance of a class in Gateway to be used in the Common package. Common has no visibility of classes in Gateway. It would create a circular dependency if Gateway was changed to depended on Common.
Keep in mind that major restructuring was not an option due to legacy code and time constraints. There are some bigger issues that are causing the problem, but I needed a simple solution for now.
To solve this problem, I made an interface in Common and changed the class in Gateway to implement that interface. As Gateway depends on Common, this is bearable. I then wired the class in Gateway into where it was needed in Common at runtime with spring using the newly created interface.
Works a treat.