Wednesday, October 31, 2018

Spring Setter Based Dependency Injection

In the post Dependency Injection in Spring I have already talked about dependency injection. Dependency Injection exists in two variants.

  • Constructor based Dependency Injection
  • Setter based Dependency Injection

In this post we'll explore one of the type of the dependency injection called Setter based Dependency Injection in Spring.

In setter based dependency injection, Spring IOC container will call setter methods on your beans after invoking a no-arg constructor or no-arg static factory method to instantiate your bean.

The <property> sub-element of <bean> is used for setter dependency injection. If you need to inject an object dependency use ref element, for primitive and String values use value element.

Spring setter based Dependency Injection Example

Let's see an example to understand it better. There is a PayServiceImpl class which uses Payment Class object to process payment, it has two fields one for Payment class object and another is amount which is an integer field.

Code for PayServiceImpl class, note that it has two fields for which values will be injected using setter dependency injection. For that reason setters are required.

 
public interface IPayService {
 void performPayment();
}
 
public class PayServiceImpl implements IPayService {
 private IPayment payment;
 private int amount;
 
 public void performPayment() {
  payment.executePayment(amount);
 }
 
 public IPayment getPayment() {
  return payment;
 }
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }

 public int getAmount() {
  return amount;
 }
 public void setAmount(int amount) {
  this.amount = amount;
 }
}

Code for CashPayment class

 
public interface IPayment {
 void executePayment(int amount);
}
 
public class CashPayment implements IPayment{
 public void executePayment(int amount) {
  System.out.println("Perform Cash Payment - " + amount); 
 }
}

XML Configuration file (XML file name - appcontext.xml)

 
<?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-4.0.xsd">
 
  <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.prog.maven_spring.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="paymentBean" class="org.netjs.prog.maven_spring.PayServiceImpl">
      <property name="payment" ref="cashPaymentBean" />
      <property name="amount" value="100" />
  </bean>
  
</beans>

Here you can see that the properties defined in the PayServiceImpl class are used in the name attribute of the property element. Note that same name as given in the class should be used in the configuration file.

To run this you can use the class App -

public class App {
    public static void main( String[] args ){   
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
         ("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("paymentBean");
        bean.performPayment();
        context.close();
    }
}

Note that it is always recommended to use interfaces rather than concrete classes, more so with Spring as whole idea of dependency injection is to have loose coupling and interfaces help in achieving that.

That's all for this topic Spring Setter Based Dependency Injection. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Run Time Injection Using Spring Expression Language(SpEL)
  2. Using depends-on Attribute in Spring
  3. Spring Example Program Using XML Configuration
  4. Wiring Collections in Spring
  5. Dependency Injection Using factory-method in Spring

You may also like-

  1. Autowiring Using Annotations in Spring
  2. Lazy Initializing Spring Beans
  3. Using Conditional Annotation in Spring Framework
  4. Spring Bean Life Cycle
  5. String in Java
  6. LinkedHashSet in Java
  7. Lambda expression examples in Java 8
  8. ReentrantLock in Java concurrency