Different Types of Bean Injection in Spring

1. Overview

Spring framework was created originally to address the complexity of enterprise applications, and it’s well known for its implementation of dependency injection. To address an enterprise java application complexity, Spring provides four key features, and one of those features is loose coupling through dependency injection. In this article we’ll explore the different types of bean injection in Spring and how it works.

2. Preparations

First we’ll include our dependencies in our pom.xml  as follows:

<dependencies>
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>4.3.12.RELEASE</version>
  </dependency>
  <dependency>		
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>			
    <version>4.0.5.RELEASE</version>
    <scope>test</scope>
  </dependency>
</dependencies>

You can see the latest dependencies HERE.

3. Dependency Injection

Traditionally, each object is responsible for creating and obtaining references to the objects it deals with, this can lead to highly coupled and hard to test code. Alternatively, with dependency injection objects are given their dependencies at creation time by some third party, which means that objects aren’t expected to create or obtain their own dependencies.

4. Configuration

Now let’s jump into writing some code to configure our beans. In this article we’ll be using java-based configuration. Keep in mind whether you use XML-based or java-based configuration, the benefits of DI are the same. Let’s write our configuration class as follows:

@Configuration
@ComponentScan("com.baeldung.ditypes")
public class RegisterarConfig {
    @Bean
    public User user() {
        return new User("Alice", 1);
    }
}

For the purpose of demonstration and before exploring the different types of dependency injection that Spring supports. Let’s write down our User class which looks like the following:

@Component
public class User {

    private String name;
    private int id;

    public User(String name, int id) {
        this.id = id;
        this.name = name;
    }

    public String register() {
        return "User" + id + ": " + name + " is registered";
    }
    //setters & getters...
}

5. Types of Dependencies Injection

Spring provides two ways to inject bean dependencies:

5.1. Constructor Injection

Constructor based injection is simply injecting a bean dependency at the time of creation; it means that the required component for wiring the bean are passed when the bean is instantiated. We’ll be using @Autowired  annotation to satisfy our bean dependencies on our user bean constructor. Let’s apply constructor based injection in the following way:

@Component
public class Registrar {
    private User user;

    @Autowired
    public Registrar(User user) {
        this.user = user;
    }

    public String register() {
        return user.register();
    }
}

5.2. Property Injection

Setter based injection (property injection) is accomplished by Spring container invoking setter method on our bean after bean instantiation. Constructor injection is favored over property injection for hard dependencies, and property injection is usually used for optional ones. Here we use an alternative way to inject dependencies to our Registrar class  using property injection:

@Autowired
public void setUser(User user) {
    this.user = user;
}

6. Testing

Now that we’ve explored both ways of dependency injection using Spring, let’s write a simple test to assure that Spring will inject our bean. Our test class looks like the following:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = RegisterarConfig.class)
public class RegisterarTest {

    @Autowired
    private Registrar reg;

    @Autowired
    private User user;

    @Test
    public void givenAutowiredAnnotation_whenSetOnField_thenRegistrarIsInjected() {
        assertNotNull(reg);
    }

    @Test
    public void givenAutowiredAnnotation_whenSetOnField_thenUserIsInjected() {
        assertEquals("User1: Alice is registered", user.register());
    }
}

7. Conclusion

In this article we discussed different types of dependency injection in Spring framework, and showed briefly how it does work.

Share

Comments

comments

Leave a Reply

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