Inject this object into another object in Spring using the XML file

Injecting this object into another object in Spring is very common when you work with projects that using Spring framework. In my previous tutorial, I mentioned Spring’s ref attribute to include a Shape object into a Drawing object, in this tutorial I’ll talk some other ways to inject this object into another object in Spring using XML file.

OK, now suppose you have a class, this class will contain one or more students, specifically as follows:

Now let’s look at the first case. I will create a class with only one student by putting student object A in the Clazz object. Normally, we will initialize as follows:

If our student object A declares a name, we can also use it with Spring’s ref attribute.

In addition to the above declaration, we can also declare as follows:

The difference between the ref attribute and the idref attribute is that: with ref attribute, you can declare the bean’s id or the bean’s name, but for idref, it is only possible to declare the bean’s id.

In addition, we have another way to declare:

Student object A created like this, called Inner Bean. Id of the bean, in this case, it does not matter, Spring does not care about it. You should only apply it in some special case. fFrom my point of view, we should not use it. Spring supports it, then I just want to tell you guys about it 😀

Code to test:

Result:

OK, now I’ll talk about the second case. We will create a class with a list of students. I will create three students A, B, C and put them into the object Clazz. As follows:

Code to test:

Result:

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

Add Comment