Initializing objects in Spring container using XML file

In this tutorial, I will guide all of you on the basic way to initial objects in the Spring container, that is: using the XML file.

I would like to work with the example that we discussed in the tutorial about Dependency Injection.

Here we have an interface named Shape:

An object implements the interface Shape named Circle:

An object Drawing to draw:

An XML configuration file for Spring in the folder src/main/resources with the content as below:

And below is the Maven project:

Initializing objects in Spring container using XML file

To work with the Spring framework, we need to add its dependencies:

OK, now we will create a Circle object first! Because this object does not depend on other objects, so we only need initial this object with an id in the Spring container:

With the Drawing object, because this object depends on the Circle object which we already created in the Spring container, so we need a way to inject the Circle object into the Drawing object.

As you can see in the code of the Drawing class, we can inject the Circle object into the Drawing object in 2 ways: by a constructor and by setShape() method. In the Spring framework, how can we do that?

First of all, you will declare the Drawing object without dependencies as declaring the Circle object:

And now we will inject the Circle object into the Drawing object by the constructor, called Constructor Injection:

Or by setShape() method, called Setter Injection.

In this way, we need to add a default constructor to the Drawing class, because Spring will use this constructor to create the Drawing object, as below:

Now, you can inject the Circle object using Setter Injection as below:

You can choose the way you prefer based on your application.

Let’s run this example.

Here I choose to use Setter Injection, which means the content of XML configuration for Spring should look like as below:

Running example class:

Result:

5/5 - (1 vote)

Add Comment