以前都是读取properties文件,现在过来分享一下读取config文件
1.新建WebSiteConfig.java
private String UserName="192.168.2.204:11211";
private String password ="":
//set get省略
2.新建中间件工具类CenterUtils.java
import java.beans.IntrospectionException;
import org.xml.sax.SAXException;
private static WebSiteConfig _WebSiteCfg;
// 网站配置
public static WebSiteConfig GetWebSiteConfig() {
try {
if (_WebSiteCfg == null) {
_WebSiteCfg = (WebSiteConfig) XMLUtil.xmlFile2Bean(
WebSiteConfig.class, Constanst.WEBROOTPATH + Constanst.WEBSITECONFIGPATH, "UTF-8");
}
} catch (IOException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
}
return _WebSiteCfg;
}
3.新建常量类Constanst
//配置文件地址 该路径是WebRoot/XConfig/jdbc.config
public static final String WEBSITECONFIGPATH = "/XConfig/jdbc.config";
public static final String WEBROOTPATH = Constanst.class
.getProtectionDomain().getCodeSource().getLocation().getPath()
.indexOf("WEB-INF") > 0 ? Constanst.class
.getProtectionDomain()
.getCodeSource()
.getLocation()
.getPath()
.substring(
0,
Constanst.class.getProtectionDomain().getCodeSource()
.getLocation().getPath().indexOf("WEB-INF/classes"))
: Constanst.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
4.测试
System.out.println(CenterUtils.GetWebSiteConfig().getUsername());//root 这里会根据jdbc.config配置节点的值,并不是类的192.168.2.204:11211";
System.out.println(CenterUtils.GetWebSiteConfig().getPassword())//1234
5配置文件jdbc.config
<?xml version="1.0" encoding="UTF-8"?>
<WebSiteConfig>
<username>root</username>
<password>1234</password>
</WebSiteConfig>
6.这中间有个jar包 XMLUtil需要
所需jar