Using spring to read configuration information in an XML file

Source: Internet
Author: User

In general, we will write some configuration information to the configuration file in order to make changes to some points of the program without modifying the source code. Here's a way to read the XML configuration file in spring, with the basic idea of defining a Java class that defines some static variables corresponding to our configuration information, and then initializes the value of the variable to the configuration value in an injected manner. The sample code is as follows:

Create a new Java class:

Package Java;public class Config {    //value to be configured public static int value = 0;//This cannot be written as static public void setValue (int i) {value = i;}}
Create a new config. file to place our configuration information

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "       http://www.springframework.org/schema/ Beans        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd       "><bean class=" java. Config "><!--configuration information--><property name=" value "><value>5</value></property></bean ></beans>
Then, in Applicationcontext.xml, you introduce CONFIG.

<import resource= "config"/>
OK, let's test our program below.

public static void Main (string[] args) {ApplicationContext applicationcontext = new Classpathxmlapplicationcontext (" Applicationcontext.xml "); System.out.println (Config.value);}
Output is 5

We can also use this approach when using SSH integrated development, and the invocation is easier because the variable is static and can be called directly from the class name.

Using spring to read configuration information in an XML file

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.