Dependency Injection Implementation in Core Java
Implement your own lightweight Dependency Injection in core Java without using any framework.
Join the DZone community and get the full member experience.Join For Free
This article will guide you to understand and build a lightweight Java application using your own Dependency Injection implementation.
Dependency Injection … DI… Inversion Of Control…IoC, I guess you might have heard these names so many times while your regular routine or specially interview preparation time that you wonder what exactly it is.
but if you really want to understand how internally it works then continue reading here.
So, What Is Dependency Injection?
Dependency injection is a design pattern used to implement IoC, in which instance variables (ie. dependencies) of an object got created and assigned by the framework.
To use DI feature a class and it's instance variables just need to add annotations predefined by the framework.
The Dependency Injection pattern involves 3 types of classes.
- Client Class: The client class (dependent class) depends on the service class.
- Service Class: The service class (dependency class) that provides service to the client class.
- Injector Class: The injector class injects the service class object into the client class.
In this way, the DI pattern separates the responsibility of creating an object of the service class out of the client class. Below are a couple more terms used in DI.
- Interfaces that define how the client may use the services.
- Injection refers to the passing of a dependency (a service) into the object (a client), this is also referred to as auto wire.
So, What Is Inversion of Control?
In short, "Don't call us, we'll call you."
- Inversion of Control (IoC) is a design principle. It is used to invert different kinds of controls (ie. object creation or dependent object creation and binding ) in object-oriented design to achieve loose coupling.
- Dependency injection one of the approach to implement the IoC.
- IoC helps to decouple the execution of a task from implementation.
- IoC helps it focus a module on the task it is designed for.
- IoC prevents side effects when replacing a module.
Class Diagram for DI Design Pattern
In the above class diagram, the Client class that requires UserService and AccountService objects does not instantiate the UserServiceImpl and AccountServiceImpl classes directly.
Instead, an Injector class creates the objects and injects them into the Client, which makes the Client independent of how the objects are created.
Types of Dependency Injection
- Constructor Injection: The injector supplies the service (dependency) through the client class constructor. In this case, Autowired annotation added on the constructor.
- Property Injection: The injector supplies the service (dependency) through a public property of the client class. In this case Autowired annotation added while member variable declaration.
- Setter Method Injection: The client class implements an interface that declares the method(s) to supply the service (dependency) and the injector uses this interface to supply the dependency to the client class.
In this case, Autowired annotation added while method declaration.
How It Works?
To understand Dependency Injection implementation, refer code snippets here, or download/clone the Tutorial shared here on GitHub.
For a better understanding of this tutorial, it's good to have basic knowledge of Annotations and reflection in advance.
Required Java Library
Before begin with the coding steps, you can create new maven project in the eclipse and add reflection dependency in pom.xml
Create User-Defined Annotations:
As described above DI implementation has to provide predefined annotations, which can be used while declaration of client class and service variables inside a client class.
Let's add basic annotations, which can be used by client and service classes:
These classes implement service interfaces and use DI annotations.
For using the DI features client class has to use predefined annotations provided by DI framework for the client and service class.
Injector class plays a major role in the DI framework. Because it is responsible to create instances of all clients and autowire instances for each service in client classes.
- Scan all the clients under the root package and all sub packages
- Create an instance of client class.
- Scan all the services using in the client class (member variables, constructor parameters, method parameters)
- Scan for all services declared inside the service itself (nested dependencies), recursively
- Create instance for each service returned by step 3 and step 4
- Autowire: Inject (ie. initialize) each service with instance created at step 5
- Create Map all the client classes Map<Class, Object>
- Expose API to get the getBean(Class classz)/getService(Class classz).
- Validate if there are multiple implementations of the interface or there is no implementation
- Handle Qualifier for services or autowire by type in case of multiple implementations.
This class heavily uses basic method provided by the java.lang.Class and org.reflections.Reflections.
This class heavily uses basic method provided by the java.lang.reflect.Field.
The autowire() method in this class is recursive method because it takes care of injecting dependencies declared inside the service classes. (ie. nested dependencies)
This class uses java.io.File to get the java files under root directory and sub directories for input package name and basic methods provided by java.lang.ClassLoader to get the list of all classes.
Application main class:
Below is the comparison with dependencies added by spring.
1. Spring boot Dependencies:
2. Dependencies in this implementation:
This article should give a clear understanding of how DI or autowire dependencies work.
With the implementation of your own DI framework, you don't need heavy frameworks like Spring Boot. If you are really not using most of the by Spring Boot or any DI framework features in your application, like Bean Life cycle Management method executions and much more heavy stuff.
You can do a lot of things which are not mentioned here, by adding more user-defined annotations for various purpose eg. like bean scopes singleton, prototype, request, session, global-session, and many more features similar to Spring framework provides.
Thanks for taking the time to read this article, and I hope this gives a clear picture of how to use and internal working of Dependency Injection.
You can download/clone the tutorial shared here on GitHub.
Opinions expressed by DZone contributors are their own.