Saturday, April 14, 2012

Judgement day weapon for circular autowiring dependency error

On recent post I demonstrated a way to resolve circular dependency error.
However, sometimes, even the mentioned solution  is not enough and redesign is not possible.

I would like to suggest a solution of Dependency Injection which will be as much loyal as possible to the Spring IoC way and will help to overcome the circular dependency error.

This means that we will have a single class that will have a reference to all the classes which need to be injected and will be responsible for the injection.

I'll try to walk you through the steps.

Assuming we have the following service classes which cause the circular error:

@Service
public class ServiceA{

@Autowire
ServiceB serviceB;
@Autowire
ServiceC serviceC;

}

@Service
public class ServiceB{

@Autowire
ServiceA serviceA;
@Autowire
ServiceC serviceC;
}

First step is to remove the @Autowire annotations, so we will move the wiring responsibility out of Spring hands.

Second step is to create a class which will hold a reference to all the classes to inject.
Such as:
@Component
public class BeansManager{

@Autowire
private ServiceA serviceA;
@Autowire
private ServiceB serviceB;
@Autowire
private ServiceC serviceC;

get...
set... 
}


Third step is to create an interface name Injectable with method inject.
public interface Injectable{
public void inject(BeansManager beansManager);
}


Forth step is to set each service class/interface to implement the injectable interface.

e.g. :

@Service
public class ServiceA implements Injectable{

ServiceB serviceB;
ServiceC serviceC;
//method to inject all the beans which were previously were injected by Spring
public void inject(BeansManager beansManager){
this.serviceB =  beansManager.getServiceB();
this.serviceC = beansManager.getServiceC(); 
}

}


Fifth and final step is to set the BeansManager to be ready for the injection.
But take a moment to think -
It's obvious that we need  a reference of all the classes which need to be injected in the BeansManager, however, how can we make sure that the following sequence is maintained:
1. All Service classes are initiated
2. BeansManager is initiated with all the services injected by Spring
3. After BeansManager initiated and exist in its steady state, call all the service classes which need injection and inject the relevant service.

Step 3 can be achieved by a method which executed after constructor finished (via @PostConstruct annotation), however the big question here is how to make sure the BeansManager is initiated last? (after all the relevant services are initiated)
The trick is to have @Autowire on the Injectable set. This way Spring will make sure that:
a. All the injectable classes are subscribed to the BeansManager for the injection
b. The BeansManager will be initiated last (after all injectable services are initiated)

public class BeansManager

//This line will guarantee the BeansManager class will be injected last
@Autowired
private Set<Injectable> injectables = new HashSet();

//This method will make sure all the injectable classes will get the BeansManager in its steady state,
//where it's class members are ready to be set
@PostConstruct
private void inject() {
   for (Injectable injectableItem : injectables) {
       injectableItem.inject(this);
   }
}

}

Make sure you understand all the magic that happened in the fifth step, it's really cool.

Note:
If you think on a way to implement even more generic mechanism that will achieve the same, please drop me a note.

Good luck!

acknowledgement:
http://stackoverflow.com/questions/7066683/is-it-possible-to-guarantee-the-order-in-which-postconstruct-methods-are-invoke

14 comments :

  1. BeansManager is de facto your own handmade tiny application-context-like container for small related subset of beans, isn't it? Or ... rather service locator.

    ReplyDelete
    Replies
    1. Yes, it's a small container with a big difference - it does not have the the circular dependency error when system begin to grow.

      Delete
  2. Step 0: redesign your services in order to *avoid* the circular dependency.

    Redesign is always an option: it doesn't mean you have to redesign the entire application, only the parts involved in the circular dependency.

    ReplyDelete
    Replies
    1. Hi Janssen,

      Thanks for your comment.

      When building large system, the service layer classes will soon use each other, since in order to keep DRY principle each has its own logic which is needed in other service.

      If possible I would appreciate if you could send me guidelines or schema for the correct service layer design.

      Delete
    2. If services start to depend on each other for their logic, either your service granularity or their level of abstraction is incorrect. From my own experience this is very hard to get right the first time. It also involves a particular 'mindset' which you need to get used to.

      A good book on this topic is "Java Application Architecture: Modularity Patterns With Examples Using OSGi" by Kirk Knoernschild (see http://techdistrict.kirkk.com/2012/03/26/java-with-a-bit-of-osgi-the-book/). Do not let the OSGi word scare you: most of the book talks about writing modular applications using plain Spring and Java (OSGi solves some of the plumbing you would to write yourself otherwise).

      Delete
  3. Thanks alot for this nice solution...

    ReplyDelete
  4. Why not call the BeanManager just MyContext, and inject that one everywhere in your application instead of millions of beans?
    Its much simpler and less coding.

    And it costs you nearly nothing since are kind of global variables, the one way or the other.
    Second thing you could do is replacing the spring configuration of MyContext by the constructor calls of the objects in MyContextImpl. That would finally solve any problem with spring.

    ReplyDelete
    Replies
    1. Hi Frank,

      Thanks for your comments :-).
      Regarding your first proposal - I guess this is possible, since in a way all the services are singletone, however, I tried to stick as close as I can to the original @Autowire formation, i.e. having declaration and binding at each bean.
      Regarding the second solution - could you please elaborate? Do you have any post about it? (If you wish I can host your post here)

      Delete
  5. Hi Gal,
    What is the final form of the BeansManager? Initially it had all the services (Injectables) declared explicitly, then we can only see a Set , so how do you populate your Set?

    ReplyDelete
    Replies
    1. As you mentioned, the services are injected by Spring into the BeansManager, so actually there is no need for the setters.
      The getters,however, are needed as an API to get the stable services into the consumers which use it.

      Delete
  6. Used this and it worked great!

    ReplyDelete
  7. Hi,
    Thanks for that, it worked like a piece of cake.
    But, i had used the bean injector in my controller class. But since its a servlet, Fortify static scan has a reported a critical error saying- Race Condition: Singleton Member Field - meaning, The class TestClass is a singleton, so the member field serviceObject is shared between users. The result is that one user could see another user's data.
    How am I to overcome this ? Any inputs / suggestions ?

    ReplyDelete
  8. I got the same problem and solved by implementing ApplicationContextAware.

    Like this:

    class ServiceB {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.serviceA = applicationContext.getBean(ServiceA.class);
    }

    }

    ReplyDelete
  9. Thank you. This solution worked for me

    ReplyDelete