setter injection vs constructor injection in Spring
May 7, 2014 00:00 · 213 words · 1 minute read
What is setter injection?
In spring you can inject the concrete dependencies with setters.
Example
applicationContext.xml
<bean name="customerRepo" class="com.inadram.repo.hibernateRepositoryImplementation"/>
<bean name="customerService" class="com.inadram.service.CustomerServiceImplementation">
<property name="customerRepository" ref="customerRepo"/>
</bean>
Therefore your customer service class can accept customer repository as an injection with setters
customer service
public class CustomerServiceImplementation implements CustomerService {
private CustomerRepository customerRepository;
public void setCustomerRepository(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Override
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
Benefits
it is easy to adopt legacy code to spring by using setter injection
What is constructor injection
You can injection the dependencies by using the constructor.
Example
applicationContext.xml
<bean name="customerRepo" class="com.inadram.repo.hibernateRepositoryImplementation"/>
<bean name="customerService" class="com.inadram.service.CustomerServiceImplementation">
<constructor-arg index="0" ref="customerRepo"/>
</bean>
index: the constructor parameter index ref: the concrete class name that we wish to inject into customer service
We need to add a constructor to the customer service class to pass the injection into it.
customer service implementation
public class CustomerServiceImplementation implements CustomerService {
private CustomerRepository customerRepository;
public CustomerServiceImplementation(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@Override
public List<Customer> findAll() {
return customerRepository.findAll();
}
}
Benefits
constructor injection force a contract between the classes, therefore consumers have to pass the required dependencies on creation time to allow using the class functionalities.
Download
Feel free to download the full source code of this example from my github.