There are two key concepts that you must understand when you start with Spring or JakartaEE/CDI–inversion of control and dependency injection.
In brief, inversion of control means letting a framework take control of the execution flow of your program to do things like create instances of your classes and inject the required dependencies.
Suppose you have to code a Java application that calculates the age of a person using their birth date. You can start by coding the logic that calculates the age as follows:
public class AgeService {
public int getAgeByBirthDate(LocalDate date) {
return Period.between(date, LocalDate.now()).getYears();
}
}
You can also code a web UI that allows users to enter a date and then click a button to calculate the corresponding age. Here's an implementation using Vaadin:
@Route("")
public class MainView extends Composite<VerticalLayout> {
private final AgeService ageService = new AgeService();
public MainView() {
DatePicker datePicker = new DatePicker("Birth date");
Button button = new Button("Calculate age");
getContent().add(datePicker, button);
button.addClickListener(event -> calculateAge(datePicker.getValue()));
}
private void calculateAge(LocalDate date) {
int age = ageService.getAgeByBirthDate(date);
String text = String.format("Age: %s years old", age);
getContent().add(new Paragraph(text));
}
}
Notice how we instantiate AgeService directly in the MainView class. Although this is not necessarily a bad thing, we can improve the code. Especially, if we use a framework such as Spring or CDI (JakartaEE).
An evident problem with the previous code is that if we wanted to write a unit test for the calculateAge method, we would end up testing code in the AgeService class as well. This is something you should avoid in unit testing. If the test fails, we want to be completely sure that the code failed in the calculateAge method, not in the AgeService class.
In unit testing, you create mocks of the classes you don't want to test and need a way to pass the mock to the tested class. In the previous example, this is not possible since ageService is instantiated in private code. To solve this, we can let clients of MainView pass the instance of AgeService in the constructor as follows:
@Route("")
public class MainView extends Composite<VerticalLayout> {
private final AgeService ageService; // no "new" keyword
public MainView(AgeService ageService) {
this.ageService = ageService;
...
}
...
}
Now, a unit test can pass a mock of AgeService. But, what happens with the actual application? Which instance is passed?
In this example application, Vaadin creates instances of MainView, when needed. It does this through either Spring or CDI, when they are used. This means that the instances are managed by these frameworks, and when you run your application, you simultaneously yield control of your application to the Spring or CDI framework. The framework then controls the flow of the application and calls your code. In the previous example, it calls the constructor of the MainView class. This is what is called inversion of control. The framework is also allowed to do other things. For example, it can pass dependencies declared in the constructor. This process is called dependency injection.
If you use Spring, you need to make sure it manages the instances of AgeService. You can do this by using the @Component or @Service annotations. For example:
@Service
public class AgeService {
...
}
If you use CDI, you don't have to add anything to the AgeService class, but you need to mark the constructor of MainView with the @Inject annotation.
Here's a video that explains in more detail the concepts covered in this article:
You can find the source code on GitHub.