
Spring Setter Injection
The Spring, setter injection is a dependency injection approach where you provide dependencies to a bean using setter methods. This is one of the two primary methods of dependency injection in Spring, with the other being constructor injection. Setter injection is often used when you have optional dependencies or when you want to modify the dependencies of a bean after it has been created. Here’s how to perform setter 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;
// Getter and setter methods for 'name'
}
public class PersonService {
private Person person;
// Setter method for 'person'
public void setPerson(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 dependencies using setter injection. You can use the <property>
element to set the values of properties or invoke setter methods.
<bean id="john" class="com.example.Person">
<property name="name" value="John" />
</bean>
<bean id="personService" class="com.example.PersonService">
<property name="person" ref="john" />
</bean>
In this XML configuration:
- We define a “john” bean of class
com.example.Person
and set the “name” property to “John” using the<property>
element. - We define a “personService” bean of class
com.example.PersonService
and set the “person” property to reference the “john” bean using the<property>
element.
3. Access the Target Bean:
You can access the target bean, “personService,” by retrieving it from the Spring application context. The “john” bean will be injected into the “person” property using the setter method.
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
PersonService personService = context.getBean("personService", PersonService.class);
// Use the personService bean, which now has a Person dependency
Setter injection allows you to provide dependencies to a bean using setter methods, giving you flexibility in configuring and modifying dependencies. It’s particularly useful when you have optional dependencies or need to update the dependencies of a bean dynamically.