InterviewSolution
| 1. |
What do you understand by Dependency Injection? |
|
Answer» The act of wiring beans together is based on a pattern known as dependency injection (DI). Rather than have COMPONENTS create and MAINTAIN the LIFECYCLE of other beans that they depend on, a dependency-injected application relies on a separate entity (the container) to create and maintain all components and inject those into the beans that need them. This is done typically through constructor arguments or property accessor methods. As per shown in the example, you can inject any EMAIL service provider and it can send an email at runtime provided the injecting class follows a valid contract. package com.knowledgehut.java; public class MyApp { private EmailServiceProvider emailProcessor = null; public MyApp(EmailServiceProvider service){ this.emailProcessor=service; } public void sendEmail(STRING message, String toEmail ){ this.emailProcessor.sendEmail(msg, toEmail); } }Some of the benefits of using Dependency Injection are Separation of Concerns, Boilerplate Code reduction, Configurable components, and easy unit testing. |
|