Initializing objects in Spring container using XML file

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

I would like to work with the example which 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 Maven project:

Initializing objects in Spring container using XML file

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

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

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

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

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

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

Or by setShape() method, called Setter Injection. With this way, we need to add a default constructor to Drawing class, because Spring will use this constructor to create Drawing object, as below:

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

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

Let run this example.

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

Running example class:


Initializing objects in Spring container using XML file


Reference this tutorial on GitHub:

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

Add Comment