I. Reading an XML configuration file
(i) Create a new Java bean (Hellobean.java)
1 PackageXX.XXX.XXX; 2 3 Public classHellobean {4 PrivateString HelloWorld; 5 6 PublicString Gethelloworld () {7 returnHelloWorld; 8 } 9 Ten Public voidSethelloworld (String helloWorld) { One This. HelloWorld =HelloWorld; A } -}
(ii) construct a configuration file (Beanconfig.xml)
1 <!---->xml version= "1.0" encoding= "UTF-8"?> 2 <!---->> 3 <beans> 4 class= "Chb.demo.vo.HelloBean" > 5 < Property name= "HelloWorld" > 6 <value>Hello!chb!value> 7 property> 8 bean> 9 beans>
(iii) reading an XML file
1. Using Classpathxmlapplicationcontext
1 New Classpathxmlapplicationcontext ("Beanconfig.xml"); 2 Hellobean Hellobean = (Hellobean) context.getbean ("Hellobean"); 3 System.out.println (Hellobean.gethelloworld ());
2. Read with Filesystemresource
1 New Filesystemresource ("D:/software/tomcat/webapps/springwebdemo/web-inf/classes/beanconfig.xml"); 2 New Xmlbeanfactory (RS); 3 Hellobean Hellobean = (Hellobean) factory.getbean ("Hellobean"); \ 4 System.out.println (Hellobean.gethelloworld ());
It is important to note that, with Filesystemresource, the configuration file must be placed in the project direct directory, or an absolute path, or an exception will be thrown that cannot find the file.
Two. Read the properties configuration file
Here are two techniques: use Spring to read the properties file and take advantage of Java.util.Properties read (i) Read properties using Spring File We also use the Hellobean.java file above to construct the following beanconfig.properties file:
1 hellobean.class=chb.demo.vo.HelloBean 2 hellobean.helloworld=hello!chb!
The "Hellobean" name in the properties file is the Bean's alias setting, and the. Class is used to specify the source of the class. Then use Org.springframework.beans.factory.support.PropertiesBeanDefinitionReader to read the properties file
1 New defaultlistablebeanfactory (); 2 New Propertiesbeandefinitionreader (reg); 3 Reader.loadbeandefinitions (new classpathresource ("Beanconfig.properties")); 4 Beanfactory factory = (beanfactory) reg; 5 Hellobean Hellobean = (Hellobean) factory.getbean ("Hellobean"); 6 System.out.println (Hellobean.gethelloworld ());
(ii) using Java.util.Properties to read a property file for example, we construct a ipconfig.properties to hold the server IP address and port, such as:
1 ip=192.168.0.1 2 port=8080
Then we can use the following procedure to obtain the server configuration information:
1InputStream InputStream = This. GetClass (). getClassLoader (). getResourceAsStream ("Ipconfig.properties"); 2Properties p =NewProperties (); 3 Try { 4 p.load (InputStream); 5}Catch(IOException E1) {6 E1.printstacktrace (); 7 } 8System.out.println ("IP:" +p.getproperty ("IP") + ", Port:" +p.getproperty ("Port");
Several ways Java reads a configuration file