Apache的Commons-configuration自动加载特性

      在一些项目可能配置文件经常变化,配置文件的类型可能为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);
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值