Cover Image for Spring Constructor Injection
136 views

Spring Constructor Injection

The Spring, constructor injection is one of the approaches for injecting dependencies into a bean. It allows you to provide the necessary dependencies to a bean’s constructor when the bean is created. Constructor injection is useful when you want to ensure that a bean has all its required dependencies when it is instantiated, making it easier to maintain and test your code. Here’s how to perform constructor injection in Spring:

1. Create the Dependent Beans:

First, create the dependent beans (dependencies) that you want to inject into another bean. These dependent beans should be defined as separate Spring beans.

For example, let’s create a Person class and a PersonService class:

public class Person {
    private String name;

    // Constructor
    public Person(String name) {
        this.name = name;
    }

    // Getter and setter methods for 'name'
}

public class PersonService {
    private Person person;

    // Constructor
    public PersonService(Person person) {
        this.person = person;
    }

    // Other methods
}

2. Configure Beans in XML:

In your Spring configuration file (e.g., applicationContext.xml), define the beans and specify the constructor injection by providing the constructor arguments using the <constructor-arg> element.

<bean id="john" class="com.example.Person">
    <constructor-arg value="John" />
</bean>

<bean id="personService" class="com.example.PersonService">
    <constructor-arg ref="john" />
</bean>

In this XML configuration:

  • We define a “john” bean of class com.example.Person and provide a constructor argument with the value “John.”
  • We define a “personService” bean of class com.example.PersonService and inject the “john” bean as a constructor argument.

3. Access the Target Bean:

You can access the target bean, in this case, “personService,” by retrieving it from the Spring application context.

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService = context.getBean("personService", PersonService.class);

// Use the personService bean

When you retrieve the “personService” bean from the context, Spring automatically injects the “john” bean into the constructor of the “PersonService” class.

Constructor injection ensures that the dependencies are provided at the time of bean creation, making it a reliable way to set up your bean with all the required components. It also promotes immutability since you can make the injected dependencies final, ensuring they cannot be changed after the bean’s instantiation.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS