Saying about XML configuration file in Spring

In Spring framework, we have a lot of ways to initializing objects in Spring container. One of them is: using XML configuration file. In this tutorial, I will show you something need to know about this XML configuration file!

We usually put the Spring XML configuration file in the folder src/main/resources.

This file is place where we will define all objects which we need Spring initial and manage them.

This file will declare the namespaces to use the XML tags, so that we need follow the structure of XML tags strictly which is defined in the schema file for the namespaces.

The basic content of the XML configuration file must have in Spring as below:

As you see, here we need define the beans so that we will declare the namespace for <bean> tag by using the schema spring-beans.xsd of Spring in attribute schemaLocation.

In Spring, for each versions, there is a specific schema for that version.

Example, if I use Spring version 4.3.x then Spring will have schema for this version at http://www.springframework.org/schema/beans/spring-beans-4.3.xsd. With Spring version 4.2.x, the schema URL will be http://www.springframework.org/schema/beans/spring-beans-4.2.xsd.

To avoid changing the schema URL each time we upgrade Spring version in our project, you only need declare schema URL without the version like: http://www.springframework.org/schema/beans/spring-beans.xsd. With this declaration, the schema will be upgraded automatically when we upgrade the Spring version in our project.

Beside <bean> tag, we can use other tags in the Spring XML configuration file. To add the namespaces for these tags, you need declare them as an attribute of <beans> tag, like the namespace “xsi” above

and schema URL for these namespaces in schemaLocation attribute.

Example, I want to use <context> tag in the Spring XML configuration file with schema URL at http://www.springframework.org/schema/context/spring-context.xsd, then I will declare as below:

You can compare the content before and after to see what is difference!

Đá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