๐๐ SPRING CERTIFICATION QUESTION: What is dependency injection and what are the advantages?
๐๐ SPRING CERTIFICATION QUESTION: What is dependency injection and what are the advantages?
๐๐๐ฉ๐๐ง๐๐๐ง๐๐ฒ ๐ข๐ง๐ฃ๐๐๐ญ๐ข๐จ๐ง ๐ is a design pattern that implements ๐๐ง๐ฏ๐๐ซ๐ฌ๐ข๐จ๐ง ๐จ๐ ๐๐จ๐ง๐ญ๐ซ๐จ๐ฅ (๐๐จ๐) design principle, whereby objects only define their dependencies letting some other code to ๐ข๐ง๐ฃ๐๐๐ญ those dependencies during object creation. That is why this process is called an inversion: an object doesn't control โ๐ฎ instantiation of its dependencies.
There are several dependency ๐ข๐ง๐ฃ๐๐๐ญ๐ข๐จ๐ง ๐ญ๐ฒ๐ฉ๐๐ฌ:
1. Constructor ๐ทโโ๏ธ injection - dependencies are provided through a constructor.
2. Setter โ๏ธ injection - dependencies are provided through an exposed setter method.
3. Field โน๏ธ injection - dependencies are injected directly in the field, with no constructor or setter method.
In Java language field injection is performed with the help of 'magical' reflection ๐ช technology, so even private fields can be populated in that way.
Fields have to be annotated with the ๐ด๐ข๐ก๐๐ค๐๐๐๐ annotation to become field injection candidates.
4. Interface ๐ค injection - dependencies are provided through an exposed setter method of the implemented interface.
5. Method ๐ฆ injection - dependencies are provided from overridden methods of container-managed bean.
Dependency injection ๐๐๐ฏ๐๐ง๐ญ๐๐ ๐๐ฌ are the following:
1. Code is cleaner ๐งผ (object configuration details are externalized)
2. Decoupling decreases ๐ between an object and its dependencies
3. Code is easier to test ๐งช using stubs or mocks
4. Facilitating single 1๏ธโฃ responsibility principle
Dependency injection ๐๐ข๐ฌ๐๐๐ฏ๐๐ง๐ญ๐๐ ๐๐ฌ are the following:
1. Increased ๐ number of classes
2. Creation of unnecessary ๐คทโโ๏ธ interfaces
#spring #certificationquestion #vcp