Talking more about Setter Injection in Spring using XML file

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

Let consider following example:

I have class Student:

and class Clazz with following content:

As you see, class Clazz contains 2 properties: an instance of Student object, 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 new Maven project:

Talking more about Setter Injection in Spring using XML filewith class Application has following content:

Spring dependency:

OK, let’s get started.

To inject Student object into Clazz object, first we need initial Student object in Spring container:

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

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

  • Name attribute is mandatory, it is name of the property which we need inject in Clazz object.
  • Value and ref attributes are same like Constructor Injection. Value attribute is used in-case injecting value is a text, number or boolean … Ref attribute is used to reference to other bean which already created in Spring container.

Result:

Talking more about Setter Injection in Spring using XML file

Beside 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 declare in the XML configuration file of Spring as below:

then using following syntax to inject the dependency objects.

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

Result:

Talking more about Setter Injection in Spring using XML file

 

Reference project on GitHub: https://github.com/huongdanjavacom/huongdanjava.com/tree/master/spring-setter-injection

Chia sẽ bài viết này ...Share on Facebook
Facebook
0Tweet about this on Twitter
Twitter
Share on LinkedIn
Linkedin

Add Comment