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 FreeOverview
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.
Prerequisite
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
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.9-RC1</version>
<scope>compile</scope>
</dependency>
<!-- other dependencies -->
</dependencies>
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:
CustomComponent.java
xxxxxxxxxx
import java.lang.annotation.*;
/**
* Client class should use this annotation
*/
RetentionPolicy.RUNTIME) (
ElementType.TYPE) (
public @interface CustomComponent {
}
CustomAutowired.java
xxxxxxxxxx
import java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Service field variables should use this annotation
*/
METHOD, CONSTRUCTOR, FIELD }) ({
RUNTIME) (
public @interface CustomAutowired {
}
CustomQualifier.java
xxxxxxxxxx
import java.lang.annotation.*;
/**
* Service field variables should use this annotation
* This annotation Can be used to avoid conflict if there are multiple implementations of the same interface
*/
ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE }) ({
RetentionPolicy.RUNTIME) (
public @interface CustomQualifier {
String value() default "";
}
Service Interfaces
UserService.java
xxxxxxxxxx
public interface UserService {
String getUserName();
}
AccountService.java
x
public interface AccountService {
Long getAccountNumber(String userName);
}
Service Classes
These classes implement service interfaces and use DI annotations.
UserServiceImpl.java
xxxxxxxxxx
import com.useraccount.di.framework.annotations.CustomComponent;
import com.useraccount.services.UserService;
public class UserServiceImpl implements UserService {
public String getUserName() {
return "shital.devalkar";
}
}
AccountServiceImpl.java
xxxxxxxxxx
import com.useraccount.di.framework.annotations.CustomComponent;
import com.useraccount.services.AccountService;
public class AccountServiceImpl implements AccountService {
public Long getAccountNumber(String userName) {
return 12345689L;
}
}
Client Class
For using the DI features client class has to use predefined annotations provided by DI framework for the client and service class.
UserAccountClientComponent.java
xxxxxxxxxx
import com.useraccount.di.framework.annotations.*;
import com.useraccount.services.*;
/**
* Client class, havin userService and accountService expected to initialized by
* CustomInjector.java
*/
public class UserAccountClientComponent {
private UserService userService;
(value = "accountServiceImpl")
private AccountService accountService;
public void displayUserAccount() {
String username = userService.getUserName();
Long accountNumber = accountService.getAccountNumber(username);
System.out.println("User Name: " + username + "Account Number: " + accountNumber);
}
}
Injector 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.
Steps:
- 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.
CustomInjector.java
This class heavily uses basic method provided by the java.lang.Class and org.reflections.Reflections.
xxxxxxxxxx
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import javax.management.RuntimeErrorException;
import org.reflections.Reflections;
import com.useraccount.di.framework.annotations.CustomComponent;
import com.useraccount.di.framework.utils.*;
/**
* Injector, to create objects for all @CustomService classes. auto-wire/inject
* all dependencies
*/
public class CustomInjector {
private Map<Class<?>, Class<?>> diMap;
private Map<Class<?>, Object> applicationScope;
private static CustomInjector injector;
private CustomInjector() {
super();
diMap = new HashMap<>();
applicationScope = new HashMap<>();
}
/**
* Start application
*
* @param mainClass
*/
public static void startApplication(Class<?> mainClass) {
try {
synchronized (CustomInjector.class) {
if (injector == null) {
injector = new CustomInjector();
injector.initFramework(mainClass);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static <T> T getService(Class<T> classz) {
try {
return injector.getBeanInstance(classz);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* initialize the injector framework
*/
private void initFramework(Class<?> mainClass)
throws InstantiationException, IllegalAccessException, ClassNotFoundException, IOException {
Class<?>[] classes = ClassLoaderUtil.getClasses(mainClass.getPackage().getName());
Reflections reflections = new Reflections(mainClass.getPackage().getName());
Set<Class<?>> types = reflections.getTypesAnnotatedWith(CustomComponent.class);
for (Class<?> implementationClass : types) {
Class<?>[] interfaces = implementationClass.getInterfaces();
if (interfaces.length == 0) {
diMap.put(implementationClass, implementationClass);
} else {
for (Class<?> iface : interfaces) {
diMap.put(implementationClass, iface);
}
}
}
for (Class<?> classz : classes) {
if (classz.isAnnotationPresent(CustomComponent.class)) {
Object classInstance = classz.newInstance();
applicationScope.put(classz, classInstance);
InjectionUtil.autowire(this, classz, classInstance);
}
}
}
/**
* Create and Get the Object instance of the implementation class for input
* interface service
*/
("unchecked")
private <T> T getBeanInstance(Class<T> interfaceClass) throws InstantiationException, IllegalAccessException {
return (T) getBeanInstance(interfaceClass, null, null);
}
/**
* Overload getBeanInstance to handle qualifier and autowire by type
*/
public <T> Object getBeanInstance(Class<T> interfaceClass, String fieldName, String qualifier)
throws InstantiationException, IllegalAccessException {
Class<?> implementationClass = getImplimentationClass(interfaceClass, fieldName, qualifier);
if (applicationScope.containsKey(implementationClass)) {
return applicationScope.get(implementationClass);
}
synchronized (applicationScope) {
Object service = implementationClass.newInstance();
applicationScope.put(implementationClass, service);
return service;
}
}
/**
* Get the name of the implimentation class for input interface service
*/
private Class<?> getImplimentationClass(Class<?> interfaceClass, final String fieldName, final String qualifier) {
Set<Entry<Class<?>, Class<?>>> implementationClasses = diMap.entrySet().stream()
.filter(entry -> entry.getValue() == interfaceClass).collect(Collectors.toSet());
String errorMessage = "";
if (implementationClasses == null || implementationClasses.size() == 0) {
errorMessage = "no implementation found for interface " + interfaceClass.getName();
} else if (implementationClasses.size() == 1) {
Optional<Entry<Class<?>, Class<?>>> optional = implementationClasses.stream().findFirst();
if (optional.isPresent()) {
return optional.get().getKey();
}
} else if (implementationClasses.size() > 1) {
final String findBy = (qualifier == null || qualifier.trim().length() == 0) ? fieldName : qualifier;
Optional<Entry<Class<?>, Class<?>>> optional = implementationClasses.stream()
.filter(entry -> entry.getKey().getSimpleName().equalsIgnoreCase(findBy)).findAny();
if (optional.isPresent()) {
return optional.get().getKey();
} else {
errorMessage = "There are " + implementationClasses.size() + " of interface " + interfaceClass.getName()
+ " Expected single implementation or make use of @CustomQualifier to resolve conflict";
}
}
throw new RuntimeErrorException(new Error(errorMessage));
}
}
InjectionUtil.java
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)
xxxxxxxxxx
import java.util.*;
import java.lang.reflect.Field;
import com.useraccount.di.framework.CustomInjector;
import com.useraccount.di.framework.annotations.*;
public class InjectionUtil {
private InjectionUtil() {
super();
}
/**
* Perform injection recursively, for each service inside the Client class
*/
public static void autowire(CustomInjector injector, Class<?> classz, Object classInstance)
throws InstantiationException, IllegalAccessException {
Set<Field> fields = findFields(classz);
for (Field field : fields) {
String qualifier = field.isAnnotationPresent(CustomQualifier.class)
? field.getAnnotation(CustomQualifier.class).value()
: null;
Object fieldInstance = injector.getBeanInstance(field.getType(), field.getName(), qualifier);
field.set(classInstance, fieldInstance);
autowire(injector, fieldInstance.getClass(), fieldInstance);
}
}
/**
* Get all the fields having CustomAutowired annotation used while declaration
*/
private static Set<Field> findFields(Class<?> classz) {
Set<Field> set = new HashSet<>();
while (classz != null) {
for (Field field : classz.getDeclaredFields()) {
if (field.isAnnotationPresent(CustomAutowired.class)) {
field.setAccessible(true);
set.add(field);
}
}
classz = classz.getSuperclass();
}
return set;
}
}
ClassLoaderUtil.java
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.
xxxxxxxxxx
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
public class ClassLoaderUtil {
/**
* Get all the classes for the input package
*/
public static Class<?>[] getClasses(String packageName) throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration<URL> resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<>();
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
dirs.add(new File(resource.getFile()));
}
List<Class<?>> classes = new ArrayList<>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes.toArray(new Class[classes.size()]);
}
/**
* Get all the classes for the input package, inside the input directory
*/
public static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
List<Class<?>> classes = new ArrayList<>();
if (!directory.exists()) {
return classes;
}
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
assert !file.getName().contains(".");
classes.addAll(findClasses(file, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
String className = packageName + '.' + file.getName().substring(0, file.getName().length() - 6);
classes.add(Class.forName(className));
}
}
return classes;
}
}
Application main class:
UserAccountApplication.java
xxxxxxxxxx
import com.useraccount.di.framework.CustomInjector;
public class UserAccountApplication {
public static void main(String[] args) {
CustomInjector.startApplication(UserAccountApplication.class);
CustomInjector.getService(UserAccountClientComponent.class).displayUserAccount();
}
}
Below is the comparison with dependencies added by spring.
1. Spring boot Dependencies:
2. Dependencies in this implementation:
Conclusion
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.
Comments