appendix-b

Appendix B. Beans and the ApplicationContext: Dependency injection in Spring

 

Every time you hear about Spring, there will be a mention of beans. Most users will be familiar with the concept, and even newcomers have an understanding that these are "special objects managed by Spring". Some Spring Boot testing techniques include manipulating those beans, and it is worth exploring what they are exactly.

One of the core technologies of Spring is its Inversion of Control container, or IoC container for short. It is designed for a specific form of IoC, called Dependency Injection (DI). The main idea of dependency injection is that if an instance of class FooService needs an instance of class BarRepository, that dependency is not created by FooService itself, but rather passed from the outside. In practice, it would look something like:

Listing B.1 Dependency injection
interface BarRepository { } #1

// Without dependency injection
class FooService {

    private final BarRepository barRepository;

    public FooService(BarRepository barRepository) {
        this.barRepository = new SqlBarRepository(); #2
    }

}

// With dependency injection
class FooService {

    private final BarRepository barRepository;

    public FooService(BarRepository barRepository) {
        this.barRepository = barRepository; #3
    }

}