Constructor-Based Dependency Injection in Spring

In this tutorial on Spring Framework you will learn 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 a Service class we have. Below is an example of a UserService class which uses Constructor-Based dependency injection to inject a Utility class.

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 which has a constructor with two arguments as Strings or primitive data types. Let’s assume we need to inject an object which has 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;
    }
    
}

To inject the above EncryptionUtils class into a UserUtils class we will use the following constructor.

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;
    }

}

but for the EncryptionUtils class to be instantiated and properly injected we will need to instantiate it either in a configuration class or in a class which is market as @SpringBootApplication.

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 would like 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, have a look at the below list of video course that teach Spring Framework.