Saturday, January 21, 2023

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.

Refer Spring Constructor Based Dependency Injection to know more about constructor 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.

In the PayServiceImpl class, there are two fields for which values are set using setter methods. Setter dependency injection is used to inject those values.

 
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. Spring Expression Language (SpEL) With Examples
  2. Spring depends-on Attribute and @DependsOn With Examples
  3. Spring XML Configuration Example
  4. Wiring Collections in Spring
  5. Dependency Injection Using factory-method in Spring

You may also like-

  1. Autowiring in Spring Using @Autowired and @Inject Annotations
  2. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation
  3. Using Conditional Annotation in Spring Framework
  4. Spring Bean Life Cycle
  5. String in Java Tutorial
  6. LinkedHashSet in Java With Examples
  7. Lambda Expression Examples in Java
  8. Java ReentrantLock With Examples