#WHAT IS? Dependency Injection

Welcome to my first article for my genre #WHAT IS?. Today I’ll show you how I started to appreciate the concept of Dependency Injection (abbreviation: DI) and my bumpy learning path.

During several coding projects at the Unversity, I never enjoyed the power of DI. As we were greenhorn developers none of our project members knew about this pattern. For using class dependencies in our source code we just created the required objects with the new operator and were happy that our code compiles and runs on our machines. Since we never wrote tests () for our code we also never felt the pain of testing business logic while using `new` several times.

When I first started to write code as an employee for an enterprise application and had to write unit tests for my code I realized how awful it is to test code where I used `new`. While looking at the JavaEE codebase and the several @Inject @Named @RequestScoped annotations I was overstrained and never took time to really understand this concept. Somehow I made use of these annotations and was able to enjoy the “magic” of injecting my class dependencies after troubleshooting lots of WELD exceptions. 

As we switched our codebase from JavaEE to Spring I wanted to understand what Spring does and why it’s an alternative for JavaEE. At its core, I realized that Spring is a DI framework and it’s like a competitor for JavaEE. With Spring I now used @Autowired instead of @Inject and had to forget the JavaEE annotations. As it was not satisfying for me to just replace some annotations and not knowing how DI works under the hood.

One of my main learning tools was the book Pro Spring 5 where the authors dedicated a whole section for the concept of DI. For a deeper understanding of DI I also purchased the Udemy course Spring Framework 5: Beginner to Guru and got a quite good insight to this topic from John Thompson the owner of www.springframework.guru. In one of the videos he cited a quote which is quite accurate for explaining DI:

 Dependency injection for five year olds

When you go and get things out of the refrigerator for yourself, you can cause problems. You might leave the door open,
you might get something Mommy or Daddy doesn’t want you to have. You might even be looking for something we don’t even have
or which has expired.

What you should be doing is stating a need, “I need something to drink with lunch”, and then we will make sure you have
something when you sit down to eat. [^1]

After working on the book and the course I can now say that I understand the magic behind this concept and have deeper knowledge about it.

With Spring or every other DI framework, you get an application context which holds your created Beans and will inject the Beans you requested in your production code.

The following simple snippet shows an example for creating a service Bean:

// Spring will automatically scan all your components and
// with the @Service annotation you tell the context that
// this class is a service Bean
@Service
public class SomeService{

  public PersonDto getPersonById(Long id){

    PersonDto result = new PersonDto();
    // ... get the data from database, modify it
    // and then return it.

    return result;
  }

}

The following Java code shows the controller side which is requesting a service bean:

@Controller
public class HomeController {

  private SomeService someService;

  // you can also omit the @Autowired annotation in the latest
  // spring version at the constructor
  @Autowired
  public HomeController(SomeService someService){
    this.someService = someService;
  }

  @RequestMapping("/home")
  public PersonDto getPersonById(@RequestParam("id") String id) {
    return someService.getPersonById(Long.valueOf(id));
  }

}

 

During the runtime of your application, the context will provide your HomeController an instance of SomeService and your controller doesn’t have to know about how an instance of SomeService is created. Furthermore, you don’t need the new operator which makes your code easier to test with e.g. Mockito framework.

If you are facing similar knowledge gaps or never heard of DI, I can highly recommend you to read this book or purchase the course.

Phil.

[^1]: John Munsch, 28 October 2009

Leave a comment

Your email address will not be published. Required fields are marked *