Let’s say what is meant by it.

Dependency injection is a process of reducing the work simpler, rather than depending on a single class, that contains the most functionality to do it.
practical example:
     Lets say we want to prepare tea, if we want to prepare tea then, we need to take the kettle with water heat it, then clean the cup, and then we need tea bags to immerse it, and finnaly sugar to add for our taste, instead of doing all this by ourself, how it will be if we ask some one else to make the tea, of our own liking, some one who is ready to provide the tea of the given specification, it reduces much of the work ?… if so, welcome to the dependency injection concept in java.

In program:

say for example i want to send a E-mail. i have a person class. and a E-mail class, in future i want to extend it to sms and as well as in fb. so.what i do initially is i create a class called person. and E-mail. also i will create some more class as for the sms and fb. now my email sending functionality is primarily depends on the E-mail class (say), in future  if i want to make any changes then i have to make changes on the e-mail clas.. the other classes like the person , sms and fb all depend on the email class, when it exist like this we say it as HARD DEPENDENCY.

so what happened when we want to change something we obviously need to change on the email class too, upon whom all the class depends on. one can easily state by providing a construction for e-mail can resolve this, so the client program accessing should also have an email class initialised in it otherwise the client program cannot use this at any cause. To over come this dependency injection is used.

What dependency injection does is, it will create a common interface, not a class, for instance, it will create something called , MessageService(){ };, such that all the other classes will implement this interface, as a result the hard dependency is reduced, what will happen is , every class will share this particular interface, but if there is any modification needed, they will make it on specific classes like fb or twiter or sms or any clases like that that will leave the MessageService() undisturbed, as a result the project will be loosely coupled, reducing the complexity.

such project can be easily tested as well. So to provide the dependency in java we use something called SPRING

public class Email {
public void sendEmail(String subject, String message){
// Send the email
}
}

Leave a Comment