Constructor-Based Dependency Injection in Spring

This tutorial will teach you how to use constructor-based dependency injection(DI) in Spring Framework when building RESTful Web Services.

Injecting an Object

Let’s assume we need to inject a Utility class into our Service class. Below is an example of a UserService class which uses a Constructor-Based dependency injection to inject a Utility class.

Notice the use of @Autowired annotation. If your class has a single constructor, then using @Autowired annotation becomes optional.

package com.appsdeveloperblog.examples.constructordi.ConstructorDI.serivce;

import com.appsdeveloperblog.examples.constructordi.ConstructorDI.UserUtils;
import com.appsdeveloperblog.examples.constructordi.ConstructorDI.model.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    UserUtils utils;
    
    @Autowired
    public UserServiceImpl(UserUtils utils)
    {
        this.utils = utils;
    }

    @Override
    public UserDTO getUser(String userId) {
        UserDTO user = new UserDTO();
        
        user.setId(utils.generateUserId());
                 
        user.setEmail("[email protected]");
        user.setFirstName("Sergey");
        user.setLastName("Kargopolov");

        return user;
    }
    
}

For a UserUtils class to be injected into a constructor of UserServiceImpl class, the UserUtils class needs to be either a @Service or a @Component. Below is a source code of UserUtils class which is annotated with @Component annotation.

package com.appsdeveloperblog.examples.constructordi.ConstructorDI;

import java.util.UUID;
import org.springframework.stereotype.Component;

@Component
public class UserUtils {
    
    public String generateUserId()
    {
        return UUID.randomUUID().toString();
    }
    
}

Constructor with Two Strings

Sometimes we need to inject an object with a constructor with two arguments: Strings or primitive data types. Let’s assume we need to inject an object with a constructor with two Strings.

Below is an example of EncryptionUtils class which we will inject into a UserServiceImpl class.

package com.appsdeveloperblog.examples.constructordi.ConstructorDI;


public class EncryptionUtils {
    
    private String keyType;
    private String certificate;
    
    public EncryptionUtils(String keyType, String certificate)
    {
        this.keyType = keyType;
        this.certificate = certificate;
    }

    public String getKeyType() {
        return keyType;
    }

    public void setKeyType(String keyType) {
        this.keyType = keyType;
    }

    public String getCertificate() {
        return certificate;
    }

    public void setCertificate(String certificate) {
        this.certificate = certificate;
    }
    
}

We will use the following constructor to inject the above EncryptionUtils class into a UserUtils class.

package com.appsdeveloperblog.examples.constructordi.ConstructorDI.serivce;

import com.appsdeveloperblog.examples.constructordi.ConstructorDI.EncryptionUtils;
import com.appsdeveloperblog.examples.constructordi.ConstructorDI.UserUtils;
import com.appsdeveloperblog.examples.constructordi.ConstructorDI.model.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    UserUtils userUtils;
    EncryptionUtils encryptionUtils;
    
    
    @Autowired
    public UserServiceImpl(UserUtils userUtils, EncryptionUtils encryptionUtils)
    {
        this.userUtils = userUtils;
        this.encryptionUtils = encryptionUtils;
    }

}

For the EncryptionUtils class to be instantiated and properly injected, we need to instantiate it either in a configuration class or in a class marked with @SpringBootApplication.

Notice the @Bean annotation used above the method. When using @Bean above the method name, Spring Framework will add an object returned by this method into Spring Application Context. Once the object is added to Spring Application Context, it can be used for dependency injection in other classes.

package com.appsdeveloperblog.examples.constructordi.ConstructorDI;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class ConstructorDiApplication {

 public static void main(String[] args) {
   SpringApplication.run(ConstructorDiApplication.class, args);
 }
        
        @Bean
        public EncryptionUtils getEncryptionUtils()
        {
            return new EncryptionUtils("3DES", "X509Certificate");
        }

}

Video Tutorial

I hope this short tutorial was helpful to you.

If you want to learn more about building RESTful Web Services with Spring Framework, please check the following page on this site: Spring Boot and Spring MVC.

If you enjoy learning by watching a series of step-by-step video lessons, look at the below list of video courses that teach Spring Framework.


Leave a Reply

Your email address will not be published.