Javatpoint Logo

91-9990449935

 0120-4256464

Javatpoint Logo

Dependency Injection by setter method

We can inject the dependency by setter method also. The <property> subelement of <bean> is used for setter injection. Here we are going to inject

  1. primitive and String-based values
  2. Dependent object (contained object)
  3. Collection values etc.

Injecting primitive and string-based values by setter method

Let's see the simple example to inject primitive and string-based values by setter method. We have created three files here:

  • Employee.java
  • applicationContext.xml
  • Test.java
Employee.java

It is a simple class containing three fields id, name and city with its setters and getters and a method to display these informations.

applicationContext.xml

We are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.

Test.java

This class gets the bean from the applicationContext.xml file and calls the display method.

Output:20 Arun ghaziabad





Latest 4 Tutorials on JavaTpoint