Inversion of control and dependency injection in Java web development.

What is dependency injection?

If one class is highly dependent on another class then we can say that both classes are tightly coupled. For example.

In the above example, the Pet class is dependent on Dog and Cat class. Now let us use an Interface.

Now, Pet class is independent of the type of animal. If we pass the Dog object then it will execute the method of Dog and if we pass another animal object then the respective method will be executed. Thus Pet class is loosely coupled with Dog and Cat class.

Dependency injection is a way to achieve loose coupling. In a complex project, if we modify code at one position then we have to modify it at several locations. With dependency injection, different classes will be decoupled and we need to modify our code at relatively much fewer positions.

Inversion of Control.

Some classes and methods are dependent on others for execution. We have to manually pass dependent classes, methods, and interfaces. When we pass a control for injecting these dependencies to third-party tools like the spring framework then we call it an inversion of control because control to passing dependency is inverted.

In the Java Spring framework, there is three-way to configure our project for Inversion of Control and passing dependency.

  1. XML configuration: In the Spring Java development process.

we first configure our java beans.

In Spring view every class is a bean. After configuration, we create a spring container.

Spring container is generally known as ApplicationContext.There are specialized implementations of ApplicationContext.Like ClassPathXmlApplicationContext, AnnotationConfigApplicationContext etc.

Then we retrieve the bean from the spring container.

2. Spring configuration using Java annotation

In the appContext.xml file, we configure the package where all java classes are present.

Register the class to Spring

with @Component annotation, the spring framework will register this class as spring bean.

We retrieve the class through the application context in the same way as in XML configuration.

3. Spring configuration with only java class with XML configuration.

Create a java class for configuration

Read the spring java configuration class in the application context.

We retrieve the bean in the same way as in the previous config. methods.

References

https://www.geeksforgeeks.org/spring-dependency-injection-with-example

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Aditya Kumar

Aditya Kumar

Hi, I am Aditya. I studied at IIT BHU Varanasi , India. I am a Java developer. I partricipate in competitive programming.