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 use the 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 about some other ways to inject this object into another object in Spring using an XML file.

First, I will create a new Maven project as an example:

I will use Java 17 for this example application:

Spring dependency is as follows:

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, we have another way to declare:

Student object A created like this, called Inner Bean. The id of the bean, in this case, does not matter, Spring does not care about it. You should only apply it in some special cases. From 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:


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:


Add Comment