Circular Dependencies In Spring
In order to understand the circular dependency scenario, we need to first understand "How Spring Inject Dependencies" in normal situation.
How Spring Inject Dependencies - Normal Situation
Let's take an example:
In our application we have beans A,B & C and they are depend on one another like below.
This is how spring resolve dependency injection process for our example scenario:
Above process illustrates by below code snippet.
Here is our Main application :
Bean Files:
But...How It Works In Circular Dependency Situation ?
For the simplicity ,Lets assume A and B two beans are depend like below:
What Happen Next??
when having a circular dependency, Spring cannot decide which of the beans should be created first, since one bean depend on one another. In those type of situations , Spring will complain my throwing "BeanCurrentlyInCreationException" while loading the application context.
But "I am not getting such exception?? Here is my code "
Yes..In this case you are using field level dependency injection.So spring is intelligent to identify such kind of scenario and it can fix the issue by itself.
- Create Bean A & B first
- Inject dependencies to each other
This is how spring documentation states the problem:
References:
No comments:
Post a Comment