We saw What is DI and its different form of Injection in our Previous Post, here we look at how Spring Dependency Injection works in Detail with Diagrammatic Representation.
Step 1 :
ApplicationContext will be Created and Configured by Reading Configuration Meta-Data.
Step 2 :
ApplicationContext will create all the Beans defined in Configuration Meta-Data.
Step 3 :
All Bean Dependencies from Properties, Constructors, Factory Bean, Factory Method will get Injected at the time of Bean Creation itself.
Note : Bean A is dependent on Bean B.
Step 4 :
Before a Bean is Created and Assembled in IoC Container, it’s dependent Bean will be Created First in IoC Container.
Beware of Circular Dependency
If Bean A Constructor Args is Bean B and Bean B’s Constructor Args is Bean A. In this case, Container will look up “Bean B” while Creating “Bean A” and “Bean A” while Creating “Bean B”. This will cause Circular Dependency and throws BeanCurrentlyInCreationException.
Key Terms :
- By Default Bean will be marked as Singleton scoped.
- All the Bean’s will get Created and assembled in ApplicationContext(IoC Container) while the container is Loading.
- ApplicationContext will read and configure Configuration Meta-Data at the time of Creation of Container.
- All the Bean Definitions are Validated at the time of Container Creation itself.
- If Bean A is Dependent on Bean B, Bean B will get Created and configured first before creating Bean A.
- All the Dependencies will be Provided to the Bean when it is Created.
- Spring can convert the Property value specified in String format to its actual Type automatically Ex., long, byte, int, boolean,…
- Bean can be Lazy loaded by specifying lazy-init in Configuration Meta-Data.
- If Bean is Lazy loaded, it will be Created and Configured only at First call of the Bean. Any Dependency issue may not figure out earlier in this approach.