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 Literal Values By Constructor Injection

Injecting literal values (like strings, numbers, booleans) into Spring beans using constructor injection can be done using the Spring XML configuration. Let's look at an example to understand how this works.

Example:

  1. Java Classes:

    Suppose we have a Person class, and we want to inject the name and age of the person using constructor injection:

    public class Person {
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public void displayInfo() {
            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
        }
    }
    
  2. XML Configuration:

    To inject the name and age of the Person class using constructor injection, you'd define the beans in the XML configuration as follows:

    <?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">
    
        <bean id="personBean" class="com.example.Person">
            <constructor-arg value="John Doe" />
            <constructor-arg value="30" />
        </bean>
    
    </beans>
    

    Here, the <constructor-arg> elements are used to pass values to the constructor of the Person class. The order of the <constructor-arg> elements should match the order of parameters in the constructor.

  3. Testing the Configuration:

    To validate the configuration and ensure that the literal values are injected properly:

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

    Running the above App class should display:

    Name: John Doe
    Age: 30
    

Note:

While XML-based configuration is showcased above, modern Spring applications often use annotations or Java-based configuration for defining beans and dependencies. However, XML-based configuration remains a valid and sometimes preferred choice in certain scenarios, especially when you want to avoid recompilation or keep configuration external to the codebase.

  1. Spring constructor injection with literal values:

    • Description: Constructor injection in Spring involves injecting dependencies through the constructor. Literal values, such as strings or numbers, can be directly injected.
    • Code:
      public class MyService {
          private String serviceName;
      
          public MyService(String serviceName) {
              this.serviceName = serviceName;
          }
      }
      
  2. Spring dependency injection for primitives in constructor:

    • Description: Primitives can be injected into a constructor in the same way as other objects. Spring automatically converts and injects the values.
    • Code:
      public class MyService {
          private int maxRetryAttempts;
      
          public MyService(int maxRetryAttempts) {
              this.maxRetryAttempts = maxRetryAttempts;
          }
      }
      
  3. Injecting constants in Spring constructor:

    • Description: Constants can be injected into a constructor using the final keyword. This ensures that the constant value remains the same throughout the object's lifecycle.
    • Code:
      public class MyService {
          private final int MAX_RETRIES;
      
          public MyService(@Value("${max.retries}") int maxRetries) {
              this.MAX_RETRIES = maxRetries;
          }
      }
      
  4. Spring framework constructor injection example:

    • Description: The Spring framework supports constructor injection as a primary method of injecting dependencies into beans. This is a fundamental feature of Spring's Inversion of Control (IoC) container.
    • Code:
      public class MyService {
          private MyRepository myRepository;
      
          public MyService(MyRepository myRepository) {
              this.myRepository = myRepository;
          }
      }
      
  5. Constructor-based dependency injection in Spring with literals:

    • Description: Combine constructor injection with literals to inject both dependencies and literal values into a bean.
    • Code:
      public class MyService {
          private String serviceName;
          private int maxRetryAttempts;
      
          public MyService(String serviceName, int maxRetryAttempts) {
              this.serviceName = serviceName;
              this.maxRetryAttempts = maxRetryAttempts;
          }
      }
      
  6. Injecting properties in Spring constructor:

    • Description: Inject properties into the constructor by specifying them as parameters. Spring automatically resolves and injects these properties.
    • Code:
      public class MyService {
          private String serviceUrl;
      
          public MyService(@Value("${service.url}") String serviceUrl) {
              this.serviceUrl = serviceUrl;
          }
      }
      
  7. Spring XML configuration for constructor injection with literals:

    • Description: In XML-based configuration, define constructor arguments within the <constructor-arg> element.
    • Code:
      <bean id="myService" class="com.example.MyService">
          <constructor-arg value="exampleService" />
          <constructor-arg value="5" />
      </bean>
      
  8. Autowired constructor injection with literals in Spring:

    • Description: Use @Autowired on the constructor along with @Value to inject literals into the constructor.
    • Code:
      public class MyService {
          private String serviceName;
          private int maxRetryAttempts;
      
          @Autowired
          public MyService(@Value("${service.name}") String serviceName,
                           @Value("${max.retries}") int maxRetryAttempts) {
              this.serviceName = serviceName;
              this.maxRetryAttempts = maxRetryAttempts;
          }
      }
      
  9. Injecting primitive values in Spring constructor:

    • Description: Inject primitive values, such as integers or booleans, directly into the constructor using @Value.
    • Code:
      public class MyService {
          private int maxRetryAttempts;
      
          public MyService(@Value("${max.retries}") int maxRetryAttempts) {
              this.maxRetryAttempts = maxRetryAttempts;
          }
      }
      
  10. Spring @Value annotation in constructor injection:

    • Description: Use @Value annotation on constructor parameters to inject values from properties files or configuration directly into the constructor.
    • Code:
      public class MyService {
          private String serviceName;
      
          public MyService(@Value("${service.name}") String serviceName) {
              this.serviceName = serviceName;
          }
      }