谈Java Properties配置文件, 是J2EE容器的命令行绑定, 还是使用Deploy自适应的绑定?

来源:互联网 发布:手绘图片软件下载 编辑:程序博客网 时间:2024/05/21 20:29

这里暂且把XML格式放在一边吧,我们来看看Java使用的最多的.properties配置文件...

今天,看到好几个J2EE的应用发布到服务器上的时候,都要在J2EE Container启动的时候,在启动的脚本上面添加启动的参数:

 -DSystemAConfigFile="XXXXX" -DSystemBConfigFile="YYYYY" -DSystemCConfigFile="ZZZZZ"

这样一来,每每有新的应用需要发布到J2EE Applicaion Server的时候,又要来修改启动脚本,并作停机和重新启动的动作...给生产带来了很大的不便...

反过来看看目前流行的做法,比如说log4j、hibernate等等都有一个很好的解决办法,就是把对应的配置文件(某个.properties的文档),放在应用的classes目录下,相关的程序会自己去读取...

看了一下,其实就是利用ClassLoader.getSystemResourceAsStream()来实现的,因为对于某一个应用,所有Class的装载,都是由一系列存在父子关系的ClassLoader来完成的...通过上面这个方法,会递归查找所需要的properties文件...作了一个代码如下:

package net.csdn.blog.xport;

import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

public class Configure {

  private static final Logger logger = LogManager.getLogger(Configure.class);

  private String propertiesFileName;
  private Properties propertiesTable;

  public Configure() {
    this.loadPropertiesTable();
  }

  public Configure(String propertiesFileName) {
    this.setPropertiesFileName(propertiesFileName);
    this.loadPropertiesTable();
  }

  public String getPropertiesFileName() {
    return this.propertiesFileName;
  }

  public void setPropertiesFileName(String propertiesFileName) {
    this.propertiesFileName = propertiesFileName;
  }

  private void loadPropertiesTable() {
    propertiesTable = new Properties();
    if (this.propertiesFileName != null && this.propertiesFileName != "") {
      try {
        /*
         * 2005/11/14, 同事发现了此处存在Bug,只能在Console模式下运行,如果是在Web方式下
         * 存在Bug...原因是此处使用了ClassLoader类别读取Resource,丢失了层级关系!
         * InputStream in =
         *   ClassLoader.getSystemResourceAsStream(this.propertiesFileName);
         * propertiesTable.load(in);
        */
        ClassLoader classLoader = Configure.class.getClassLoader();
        URL resUrl = classLoader.getResource(this.propertiesFileName);
        /*
         * 虽然拿到了URL, 不好用new FileInputStream(URL.toString())来操作,因为在Windows
         * 和*NIX上面,对file:///协议的表示是不兼容的。java.net.URL会把Windows上面的文件
         * 地址解释为file:/D:/xxx/,这样就错了,正确的应该是file:///D:/xxx !
         *
         * 所以,既然有了URL对象,就可以直接openStream了!
         */
        InputStream in = resUrl.openStream();
        propertiesTable.load(in);
      }
      catch (Exception ex) {
        logger.debug(ex.getMessage(), ex);
        logger.info("can not load properties file:" + this.propertiesFileName);
      }
    }
  }

  public String getProperty(String propertyName) {
    return this.propertiesTable.getProperty(propertyName);
  }

}

这样,就可以直接修改.properties文件,就可以生效了,不用重开服务器!而且,多个应用之间的配置都是隔离开的,每个配置文件都是随着自己所在的WAR绑定的!对 one AP Server <--> multi Applications 再好不过了!

自己给这个起了个名字,叫做“自适应配置文件读取”!

原创粉丝点击