DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Introduction to Apache Kafka With Spring
  • Preact With InversifyJS for Dependency Injection
  • Micronaut With Relation Database and...Tests
  • Dependency Injection in Spring

Trending

  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • AI Speaks for the World... But Whose Humanity Does It Learn From?
  • Driving DevOps With Smart, Scalable Testing
  • Ensuring Configuration Consistency Across Global Data Centers
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Understanding Inversion of Control and Dependency Injection

Understanding Inversion of Control and Dependency Injection

In this article, learn to understand inversion of control and dependency injection.

By 
Alejandro Duarte user avatar
Alejandro Duarte
DZone Core CORE ·
Mar. 12, 20 · Tutorial
Likes (13)
Comment
Save
Tweet
Share
36.9K Views

Join the DZone community and get the full member experience.

Join For Free

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:

Java
 




xxxxxxxxxx
1


 
1
public class AgeService {
2
 
          
3
    public int getAgeByBirthDate(LocalDate date) {
4
        return Period.between(date, LocalDate.now()).getYears();
5
    }
6
 
          
7
}



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:

Java
 




xxxxxxxxxx
1
21


 
1
@Route("")
2
public class MainView extends Composite<VerticalLayout> {
3
 
          
4
    private final AgeService ageService = new AgeService();
5
 
          
6
    public MainView() {
7
        DatePicker datePicker = new DatePicker("Birth date");
8
        Button button = new Button("Calculate age");
9
        getContent().add(datePicker, button);
10
 
          
11
 
          
12
        button.addClickListener(event -> calculateAge(datePicker.getValue()));
13
    }
14
 
          
15
    private void calculateAge(LocalDate date) {
16
        int age = ageService.getAgeByBirthDate(date);
17
        String text = String.format("Age: %s years old", age);
18
        getContent().add(new Paragraph(text));
19
    }
20
 
          
21
}



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).

You may also like: Spring Framework Basics: What Is Inversion of Control?

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 theAgeService 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:

Java
 




xxxxxxxxxx
1
14


 
1
@Route("")
2
public class MainView extends Composite<VerticalLayout> {
3
 
          
4
    private final AgeService ageService; // no "new" keyword
5
 
          
6
    public MainView(AgeService ageService) {
7
        this.ageService = ageService;
8
 
          
9
        ...
10
    }
11
 
          
12
    ...
13
 
          
14
}



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:

Java
 




xxxxxxxxxx
1


 
1
@Service
2
public class AgeService {
3
4
    ...
5
6
}



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.

Inversion of control Dependency injection Spring Framework unit test application

Published at DZone with permission of Alejandro Duarte. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Introduction to Apache Kafka With Spring
  • Preact With InversifyJS for Dependency Injection
  • Micronaut With Relation Database and...Tests
  • Dependency Injection in Spring

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!