𝐃𝐞𝐩𝐞𝐧𝐝𝐞𝐧𝐜𝐲 𝐢𝐧𝐣𝐞𝐜𝐭𝐢𝐨𝐧 💉 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