设为首页 收藏本站
查看: 733|回复: 0

[经验分享] Apache的Commons-configuration自动加载特性

[复制链接]

尚未签到

发表于 2017-1-7 08:41:48 | 显示全部楼层 |阅读模式
  在一些项目可能配置文件经常变化,配置文件的类型可能为xml,或者properties文件等,我们系统会自动检测到配置文件的变化,自动更新到内存等中,可以采用Apache 的commons-confiugrations实现相关的功能。如在Tomcat中web.xml配置文件的变化,tomcat会自动加载。
  在commons-configuration中自动保存代码如下:

PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setAutoSave(true);
config.setProperty("colors.background", "#000000); // the configuration is saved after this call

  自动加载代码如下:

PropertiesConfiguration config = new PropertiesConfiguration("usergui.properties");
config.setReloadingStrategy(new FileChangedReloadingStrategy());

  FileChangedReloadingStrategy中重点代码如下:

public boolean reloadingRequired() {
if (!reloading) {
long now = System.currentTimeMillis();
if (now > lastChecked + refreshDelay) {
lastChecked = now;
if (hasChanged())
reloading = true;
}
}
return reloading;
}
  在web项目写一个servlet类测试属性文件变化,并自动加载。

package com.easyway.app.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
public class ConfigurationServlet extends HttpServlet {
/**
* Constructor of the object.
*/
public ConfigurationServlet() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//从上下文中获取
PropertiesConfiguration propconfig=(PropertiesConfiguration)this.getServletContext().getAttribute("propconfig");
//打印信息到页面
String username=propconfig.getString("username");
out.println("用户的名称为:username ="+username);
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
PropertiesConfiguration propconfig=(PropertiesConfiguration)this.getServletContext().getAttribute("propconfig");
String username=propconfig.getString("username");
out.println("username ="+username);
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occure
*/
public void init() throws ServletException {
//读取配置的文件的名称
ServletContext servletContext = this.getServletContext();
String filename=servletContext.getInitParameter("appconfig");
System.out.println("filename"+filename);
//创建自动加载的机制
PropertiesConfiguration propconfig=null;
try {
propconfig = new PropertiesConfiguration(filename);
//设置编码
propconfig.setEncoding("UTF-8");
//设置自动冲加载机制
propconfig.setReloadingStrategy(new FileChangedReloadingStrategy());
//设置到ServletContext便于使用时候获取
servletContext.setAttribute("propconfig", propconfig);
} catch (ConfigurationException e) {
e.printStackTrace();
}
}
}

  web.xml配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>appconfig</param-name>
<param-value>jdbc.properties</param-value>
</context-param>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>configurationServlet</servlet-name>
<servlet-class>com.easyway.app.servlet.ConfigurationServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>configurationServlet</servlet-name>
<url-pattern>/configurationServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


<?xml version="1.0" encoding="UTF-8"?>
<origin dataSource="ds">
<columns>
<column code="ID" name="" type="java.lang.Integer" length="" />
<column code="FIRSTNAME" name="" type="java.lang.String" length="" />
<column code="LASTNAME" name="" type="java.lang.String" length="" />
<column code="SEX" name="" type="java.lang.String" length="" />
</columns>
</origin>

XMLConfiguration config = new XMLConfiguration(String); //关于XML的读取在“commons-configuration的使用”中讲过
String id = config.getString("columns.column.[@code]");   //拿到第一个Column的code
String type = config.getString("columns.column.[@type]"); //拿到第一个Column的type
Object value = ConvertUtils.convert(id,Class.forName(type)); //转换了
  背景:开发一个使用xml配置文件来处理跨数据库的数据操作。例如,我本地有一个mysql数据库叫A,里面有一个表叫test,test有两个字段,fistName和lastName;另一个服务器上有一个Oracle数据库叫B,里面有两个表,test1,test2,他两的结构是一样的,都有,Name这个字段;现在就是要把A中的表test里的fistName和lastName做字符串连接,然后存到B中的表test1,test2的Name字段。
  

commons-configuration的使用
  得到XMLConfiguration 的几种方式

XMLConfiguration config  = new XMLConfiguration(String);
XMLConfiguration config = new XMLConfiguration();
config.load(String);
  
我自己是不喜欢操作xml的,所以就没有使用dom4j和jdom的习惯。使用commons-configuration令我最爽的地方是指针式的访问方式,例如,在如下xml中,如果你得到code属性的值,只需要写如下Java代码

List codes = config.getList("columns.column.[@code]");
  <?xml version="1.0" encoding="UTF-8"?>
<origin dataSource="ds">
<columns>
<column code="ID" name="" type="java.lang.Integer" length="" />
<column code="FIRSTNAME" name="" type="java.lang.String" length="" />
<column code="LASTNAME" name="" type="java.lang.String" length="" />
<column code="SEX" name="" type="java.lang.String" length="" />
</columns>
</origin>
  
如果你的得到的字符串中有逗号,那么他会以","分割,只会得到第一个字符串。所以你必须用"\"转义,例如

String array = config.getString("config.array"); //array="10",并不是10,20,30,40
String scalar = config.getString("config.scalar"); // scalar="3,1415"
String text = config.getString("config.cite.[@text]"); // text ="To be or not to be, this is the question!"

<config>
<array>10,20,30,40</array>
<scalar>3\,1415</scalar>
<cite text="To be or not to be\, this is the question!"/>
</config>
  
默认情况下,config以","分割字符串,其实还可以使用如下方法(AbstractConfiguration 是XMLConfiguration 的父类)

AbstractConfiguration.setListDelimiter(char listDelimiter) //设置限定符
AbstractConfiguration.setDelimiterParsingDisabled(boolean) //设置限定符是否有效
  
注意:以上方法的设置要xml文件load之前(换而言之,是不能使用XMLConfiguration config = new XMLConfiguration(String)),否则,此次设置将无效,正确使用如下方式

XMLConfiguration config = new XMLConfiguration();
config.setDelimiterParsingDisabled(true);
try {
config.load(path);
} catch (Exception e) {
// TODO Auto-generated catch block
logger.error("载入文件出错",e);
}
  
还有一个比较常用的方法,例如你想把column中的属性全部取出到一个叫Bean的Java类中,你就必须定位到column,这时常用以下方式

List<HierarchicalConfiguration>  columns = (List<HierarchicalConfiguration>) config.configurationsAt("origin.columns.column");
List Beans = new ArrayList(columns.size());
for (int i = 0; i < columns.size(); i++) {
HierarchicalConfiguration column = (HierarchicalConfiguration)columns.get(i);
Bean bean = new Bean();
bean.setCode(column.getString("[@code]"));
bean.setName(column.getString("[@name]"));
...
...
beans.add(bean);
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-324895-1-1.html 上篇帖子: Apache中的文件与目录(1) 下篇帖子: Apache中 RewriteCond 规则参数介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表