Spring Boot Tutorial

Spring Boot - Software Setup and Configuration (STS/Eclipse/IntelliJ)

Prerequisite (Spring Core Concepts)

Spring Boot Core

Spring Boot with REST API

Spring Boot with Database and Data JPA

Spring Boot with Kafka

Spring Boot with AOP

Spring - Injecting Objects By Constructor Injection

Injecting objects (i.e., dependencies) using constructor injection in Spring involves passing other beans as constructor arguments. This is a fundamental aspect of Dependency Injection and Inversion of Control provided by Spring.

Let's consider an example where a Person has an Address:

1. Java Classes:

First, we have the Address class:

public class Address {
    private String street;
    private String city;

    public Address(String street, String city) {
        this.street = street;
        this.city = city;
    }

    @Override
    public String toString() {
        return street + ", " + city;
    }
}

Next, the Person class which depends on Address:

public class Person {
    private String name;
    private Address address;

    public Person(String name, Address address) {
        this.name = name;
        this.address = address;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Address: " + address);
    }
}

2. XML Configuration:

Now, let's define these beans and their dependencies in the XML configuration:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Definition for the address bean -->
    <bean id="addressBean" class="com.example.Address">
        <constructor-arg value="123 Main St" />
        <constructor-arg value="Anytown" />
    </bean>

    <!-- Definition for the person bean -->
    <bean id="personBean" class="com.example.Person">
        <constructor-arg value="John Doe" />
        <constructor-arg ref="addressBean" />
    </bean>

</beans>

Here:

  • For the addressBean, we are using constructor-args with literal values.
  • For the personBean, the first <constructor-arg> injects a literal value for the name. The second <constructor-arg> injects the addressBean object using the ref attribute.

3. Testing the Configuration:

To test the setup:

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        
        Person person = (Person) context.getBean("personBean");
        person.displayInfo();
    }
}

On execution, this should display:

Name: John Doe
Address: 123 Main St, Anytown

Note:

Constructor injection is particularly useful when the dependency is mandatory for the bean's operation. In scenarios where the dependency is optional or can have a default value, setter injection might be more appropriate. As always, the choice between constructor and setter injection should be guided by the specific needs and design of the application.

  1. Spring constructor injection for objects:

    Constructor injection in Spring involves passing dependencies through a class's constructor. Here's an example:

    public class UserService {
        private final UserRepository userRepository;
    
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        // Other methods using userRepository
    }
    
  2. Dependency injection of objects in Spring constructor:

    In this example, a UserService class is injected with a UserRepository object through its constructor.

    public class UserService {
        private final UserRepository userRepository;
    
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        // Other methods using userRepository
    }
    
  3. Spring framework constructor injection example with objects:

    The Spring framework facilitates constructor injection by automatically resolving and injecting dependencies.

    @Service
    public class UserService {
        private final UserRepository userRepository;
    
        @Autowired
        public UserService(UserRepository userRepository) {
            this.userRepository = userRepository;
        }
    
        // Other methods using userRepository
    }
    
  4. Injecting custom classes in Spring constructor:

    You can inject custom classes as dependencies in the constructor. For example:

    public class OrderService {
        private final PaymentGateway paymentGateway;
    
        public OrderService(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  5. Constructor-based dependency injection in Spring with objects:

    Spring supports constructor-based dependency injection for objects, ensuring that dependencies are provided during object creation.

    @Service
    public class OrderService {
        private final PaymentGateway paymentGateway;
    
        @Autowired
        public OrderService(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  6. Spring bean configuration for constructor injection with objects:

    XML configuration in Spring for constructor injection:

    <beans>
        <bean id="orderService" class="com.example.OrderService">
            <constructor-arg ref="paymentGateway"/>
        </bean>
    
        <bean id="paymentGateway" class="com.example.PaymentGateway"/>
    </beans>
    
  7. Autowired constructor injection with objects in Spring:

    Spring's @Autowired annotation can be used for constructor injection:

    @Service
    public class OrderService {
        private final PaymentGateway paymentGateway;
    
        @Autowired
        public OrderService(PaymentGateway paymentGateway) {
            this.paymentGateway = paymentGateway;
        }
    
        // Other methods using paymentGateway
    }
    
  8. Spring XML configuration for object injection by constructor:

    XML configuration for constructor injection in Spring:

    <beans>
        <bean id="userService" class="com.example.UserService">
            <constructor-arg ref="userRepository"/>
        </bean>
    
        <bean id="userRepository" class="com.example.UserRepository"/>
    </beans>
    
  9. Injecting beans by constructor in Spring:

    Constructor injection is a common practice for injecting beans in Spring:

    @Service
    public class ProductService {
        private final ProductRepository productRepository;
    
        @Autowired
        public ProductService(ProductRepository productRepository) {
            this.productRepository = productRepository;
        }
    
        // Other methods using productRepository
    }
    
  10. Creating and injecting custom objects in Spring constructor:

    You can create and inject custom objects through the constructor:

    @Service
    public class ShoppingCartService {
        private final DiscountCalculator discountCalculator;
    
        @Autowired
        public ShoppingCartService(DiscountCalculator discountCalculator) {
            this.discountCalculator = discountCalculator;
        }
    
        // Other methods using discountCalculator
    }