Dependency Injection Implementation in Core Java

Shital Devalkar
Globant
Published in
9 min readJan 12, 2021

Implement your own lightweight Dependency Injection in core Java without using any framework

Overview

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.

“purpose” of this article just is to make your life easy to understand how DI could work internally in springboot as per my experience in springboot and java) and not to compare with DI in springboot.

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

Class Diagram of Dependency Injection 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.

Prerequisite

For a better understanding of this tutorial, it’s good to have basic knowledge of Annotations and reflection in advance.

Required java library to be added in the classpath:

Before begin with the coding steps, you can create new “maven project” in eclipse and or other IDE and copy below below configuration to pom.xml

Note: 
to reflect below config below configuration please follow
below steps.

Right click on your project -> Maven -> Update Project

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion>
<groupId>temp</groupId>
<artifactId>com.di</artifactId>
<version>0.0.1-SNAPSHOT</version>
<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>
</project>

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.javaimport java.lang.annotation.*;/** Client class should use this annotation */@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomComponent {
}
CustomAutowired.javaimport java.lang.annotation.*;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Service field variables should use this annotation */@Target({ METHOD, CONSTRUCTOR, FIELD })
@Retention(RUNTIME)
@Documented
public @interface CustomAutowired {
}
CustomQualifier.javaimport 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
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE,
ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface CustomQualifier {
String value() default "";
}
CustomApplication.java/**
* Client class should use this annotation
*/
import java.lang.annotation.*;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface CustomApplication {
}

Service Interfaces

UserService.javapublic interface UserService {
String getUserName();
}
AccountService.javapublic interface AccountService {
Long getAccountNumber(String userName);
}

Service Implementation Classes:

These classes implement service interfaces and use DI annotations.

UserServiceImpl.java@CustomComponent
public class UserServiceImpl implements UserService {
@Override
public String getUserName() {
return "shital.devalkar";
}
}
AccountServiceImpl.java@CustomComponent
public class AccountServiceImpl implements AccountService {
@Override
public Long getAccountNumber(String userName) {
return 12345689L;
}
}

Client Classes:

For using the DI features client class has to use predefined annotations provided by DI framework for the client and service class.

ClientApplication.java

/** Client class, havin userService and accountService 
* expected to initialized by CustomInjector.java
*/
@CustomComponent
public class ClientApplication {
@CustomAutowired
private UserService userService;

@CustomAutowired
@CustomQualifier(value = "accountServiceImpl")
private AccountService accountService;
public void displayUserAccount() {
String username = userService.getUserName();
Long accountNumber = accountService.getAccountNumber(username);
System.out.println("\nUser Name: " + username
+ " Account Number: " + accountNumber);
}
}

Injector class:

CustomInjector class 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 followed by this class to create instances and inject the dependencies:

  1. Scan all the clients under the root package and all sub packages
  2. Create an instance of client class.
  3. Scan all the services using in the client class (member variables, constructor parameters, method parameters)
  4. Scan for all services declared inside the service itself (nested dependencies), recursively
  5. Create instance for each service returned by step 3 and step 4
  6. Autowire: Inject (ie. initialize) each service with instance created at step 5
  7. Create Map all the client classes Map<Class, Object>
  8. Expose API to get the getBean(Class classz)/getService(Class classz).
  9. Validate if there are multiple implementations of the interface or there is no implementation
  10. Handle Qualifier for services or autowire by type in case of multiple implementations.

Utility classes required in Injector class:

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)

InjectionUtil.java

import java.util.*;
import java.util.Map.Entry;
import java.lang.reflect.Field;
import java.util.stream.Collectors;
import javax.management.RuntimeErrorException;
public class InjectionUtil {
/**
* Perform injection recursively, for each service inside
* the client class
*/
public static void autowire(Class<?> classz,
Object classInstance, Map<Class<?>, Object> applicationScope,
Map<Class<?>, Class<?>> diMap)
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 = getBeanInstance(field.getType(), diMap,
applicationScope, field.getName(), qualifier);
field.set(classInstance, fieldInstance);

autowire(fieldInstance.getClass(),
fieldInstance, applicationScope, diMap);
}
}
/**
* Overload getBeanInstance to handle qualifier and autowire
* by type
*/
public static <T> Object getBeanInstance(Class<T> interfaceClass,
Map<Class<?>, Class<?>> diMap,
Map<Class<?>, Object> applicationScope, String fieldName,
String qualifier)
throws InstantiationException, IllegalAccessException {

Class<?> implementationClass =
getImplimentationClass(interfaceClass, diMap,
fieldName, qualifier);
if(applicationScope.containsKey(implementationClass)){
return applicationScope.get(implementationClass);
}

Object service = implementationClass.newInstance();
applicationScope.put(implementationClass, service);
return service;
}
/**
* Get the name of the implimentation class for input
* interface service
*/
private static Class<?> getImplimentationClass(Class<?>
interfaceClass, Map<Class<?>, Class<?>> diMap,
String fieldName, String qualifier) {
Set<Entry<Class<?>, Class<?>>> implementationClasses =
diMap.entrySet().stream()
.filter(entry -> entry.getValue() == interfaceClass)
.collect(Collectors.toSet());

String errorMessage = "";
if(implementationClasses == null ||
implementationClasses.isEmpty()) {
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));
}
/**
* 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.

import java.io.*;
import java.util.*;
import java.net.URL;
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;
}
}

CustomInjector.java

This class heavily uses basic methods provided by the java.lang.Class and org.reflections.Reflections.

import java.util.*;
import java.io.IOException;
import org.reflections.Reflections;
/**
* Injector, to create objects for all @CustomService classes
* autowire/inject all dependencies
*/
public class CustomInjector {
private Map<Class<?>, Class<?>> diMap;
private Map<Class<?>, Object> applicationScope;
public CustomInjector() {
super();
diMap = new HashMap<>();
applicationScope = new HashMap<>();
}
public <T> T getService(Class<T> classz) {
try{
return this.getBeanInstance(classz);
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
/** initialize the injector framework */
public 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(classz, classInstance,
applicationScope, diMap);
}
}
}
/**
* Create and Get the Object instance of the implementation
* class for input interface service
*/
@SuppressWarnings("unchecked")
private <T> T getBeanInstance(Class<T> interfaceClass) throws
InstantiationException, IllegalAccessException {
return (T) InjectionUtil.getBeanInstance(interfaceClass,
diMap, applicationScope, null, null);
}
}

DIApplication.java

This class scan for the main class having @CustomApplication annotation on the main class, if this annotation is present on the main class then Dependency Injection is taken care otherwise the main class will work like regular main java class

public class DIApplication {
private final CustomInjector injector;
public DIApplication() {
super();
this.injector = new CustomInjector();
}
public void run(Class<?> mainClassz) {
boolean hasCustomApplicationAnnotation =
mainClassz.isAnnotationPresent(CustomApplication.class);
if(hasCustomApplicationAnnotation) {
System.out.println("Starting CustomDemoApplication...");
this.startApplication(mainClassz);
this.injector
.getService(ClientApplication.class).displayUserAccount();
System.out.println("\nStopping CustomDemoApplication...");
}else{
System.out.println("\nRunning as regular java Application...");
}
}
/**
* Start application
* @param mainClass
*/
public void startApplication(Class<?> mainClass) {
try {
synchronized (DIApplication.class) {
this.injector.initFramework(mainClass);
System.out.println("\nCustomDemoApplication Started....");
}
}catch (Exception ex) {
ex.printStackTrace();
}
}
public static void run(Class<?> mainClassz, String[] args){
new DIApplication().run(mainClassz);
}
}

Application main class …last but not list !!!

MainApplicationClass.java@CustomApplication
public class MainApplicationClass {
public static void main(String[] args) {
DIApplication
.run(MainApplicationClass.class, args);
}
}

Below is the comparison with dependencies added by spring.

1. Spring boot Dependencies:

2. Dependencies in this implementation:

Create User-Defined Annotations:

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.

--

--