Spring Setter Injection

What is the Spring Setter Injection?

Spring Framework allows to inject the dependency by setter method also. The subelement of is used for setter injection

There are following values injected through setter injection.

  • Primitive Values
  • Dependent Object
  • Collection values
    Here I am taking example to inject Primitive values using Setter injection.


  • Employee.java:

  • applicationContext.xml:
    This file contains the entry for Employee class.

  • Test.java:
    This file contains the code to obtain emp bean from applicationContext.xml.

Spring Framework provides following elements to inject collection values inside element.

• list
• map
• set

Collection elements can be primitive or object collections.Here we’re taking example of Question class which has multiple answers.

Question.java
Question class has collection of String for multiple answers.

  • applicationContext.xml:
    This file contains bean entry for Question class.
  • Test.java:
    This file contains the code to obtain the object of Question from applicationContext.xml.

Spring Framework allows to inject primitive or Object references with collection.There are three XML elements available for this.
• < list >
• < set >
• < map >

  • Syntax For Primitive values Collection
    Here is syntax to define collection of primitive values.

  • Syntax For Object values Collection
    Here is syntax to define collection of object values.

  • In this example, we are taking the example of Customer and Address where Customer one or more addresses.
    Customer.java:

  • Address.java:

  • applicationContext.xml:

  • Test.java:

For Dependent Object injection we have HAS-A relation scenario.In our case there is dependency of Address object in Customer class. element has an attribute called ref to inject dependent object.
Customer.java

  • Address:
  • applicationContext.xml
    This file contains the bean entry for Customer bean.
  • Test.java
    This file has code to get the object of cust bean from applicationContext.xml.