一、如果只是讀取
新建一個 xml 文件,需要滿足Spring格式:
<?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-4.2.xsd "> <bean class="com.example.Config"> <property name="Address"> <value>中國四川省綿陽市</value> </property> </bean> </beans>
創建一個類,類的路徑與上面xml文件中的class一致:
package com.example public class Config { public static String address; public void setAddress(String addr) { address = addr; } }
然后將 config.xml 引入到Spring主配置文件中:
<import resource="config.xml"/>
測試:
System.out.println(Config.address);
二、讀寫
以config.xml為例:
<config> <Address>中國四川省綿陽市</Address> </config>
這時需要用到 jdom,代碼如下:
/* 引入項 import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.springframework.core.io.ClassPathResource; */ private String readServerConfig(String configFileName) throws Exception { ClassPathResource resource = new ClassPathResource(configFileName); Document doc = new SAXBuilder().build(resource.getFile()); Element root = doc.getRootElement(); Element element = root.getChild("Address"); return element.getText(); } private void writeServerConfig(String configFileName) throws Exception { ClassPathResource resource = new ClassPathResource(configFileName); Document doc = new SAXBuilder().build(resource.getFile()); Element root = doc.getRootElement(); Element element = root.getChild("Address"); element.setText("中國四川省成都市"); root.setContent(element); }