Categories
Spring Spring Core

How Dependency Injection works in Spring

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 : 

  1. By Default Bean will be marked as Singleton scoped. 
  2. All the Bean’s will get Created and assembled in ApplicationContext(IoC Container) while the container is Loading. 
  3. ApplicationContext will read and configure Configuration Meta-Data at the time of Creation of Container. 
  4. All the Bean Definitions are Validated at the time of Container Creation itself.
  5. If Bean A is Dependent on Bean B, Bean B will get Created and configured first before creating Bean A.
  6. All the Dependencies will be Provided to the Bean when it is Created.
  7. Spring can convert the Property value specified in String format to its actual Type automatically Ex., long, byte, int, boolean,…
  8. Bean can be Lazy loaded by specifying lazy-init in Configuration Meta-Data.
  9. 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.

Happy Reading!!!

Leave a Reply

Your email address will not be published. Required fields are marked *