Talking more about Setter Injection in Spring using XML file

In the previous tutorial, I already introduced you all the basic knowledge about Setter Injection in Spring using an XML file. In this tutorial, I will mention more details about it to help you can use it easily!

Let’s consider the following example:

I have the Student class:

and the Clazz class with the following content:

As you see, Clazz class contains 2 properties: an instance of the Student class, a variable type String, and some Setter methods to assign the value to these 2 properties. So, how we can inject these objects into class Clazz using the Setter methods?

First of all, I will create a new Maven project:

with class Application has the following content:

I will use Java 17 for this example:

Spring dependency:

OK, let’s get started.

To inject the Student object into the Clazz object, first, we need to initialize the Student object in the Spring container:

And now, to initialize the Clazz object in the Spring container, I will declare as below:

In the above declaration, I used <property> tag with pair of attributes <name, value> and <name, ref>. Inside:

  • The name attribute is mandatory, it is the name of the property which we need to inject into the Clazz object.
  • Value and ref attributes are the same as Constructor Injection. The value attribute is used in case injecting value is a text, number or boolean … Ref attribute is used to refer to another bean which already been created in the Spring container.

Result:

Besides that, same like Constructor Injection, Spring also supports us namespace p to declare Setter Injection simpler.

This namespace allows us can declare properties of objects inside the <bean> tag as attributes. There is no XSD schema file for this namespace. To use it, you only need to declare in the XML configuration file of Spring as below:

then using the following syntax to inject the dependency objects.

You should declare an attribute in <bean> tag beginning with “p:”, next is the name of an attribute of the object and end with “-ref” in case the dependency object is other beans in Spring container, then assign for it a value. For example, I can declare the Clazz object as below:

Result:

Add Comment