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