转--项目启动时加载自定义properties

来源:互联网 发布:用c 做界面编程 编辑:程序博客网 时间:2024/06/06 01:07

首先创建一个类 
public class ContextInitListener implements ServletContextListener 
使得该类成为一个监听器。用于监听整个容器生命周期的,主要是初始化和销毁的。

类创建后要在web.xml配置文件中增加一个简单的监听器配置,即刚才我们定义的类。 
Xml代码

复制代码
<listener>     <!-- lang: xml -->    <description>ServletContextListener</description>     <!-- lang: xml -->    <listener-class>com.test.web.filter.ContextInitListener</listener-class>     <!-- lang: xml --></listener>
复制代码

配置好监听器后我们开始编写ContextInitListener 的代码。实现接口后会自动生成两个方法,初始化和销毁,我们就只贴出这个吧,另一个没什么用。web项目通常来说,一般来说相对路径是在WEB-INF/classes,获取该路径下的文件,最好用getClass().getResourceAsStream(“/baseconfig.properties”);比较简单。

Java代码

复制代码
    @Override         public void contextInitialized(ServletContextEvent sce) {             Properties props = new Properties();             InputStream inputStream = null;             try {                 inputStream = getClass().getResourceAsStream("/baseconfig.properties");                 props.load(inputStream);                 String tempPath = (String) props.get("path");             } catch (IOException ex) {                 ex.printStackTrace();             }         }
复制代码

原文:http://my.oschina.net/u/585275/blog/109227

另外,若需要实现对配置文件的热加载,即项目启动后自动跟踪配置文件的修改,则可以这样写:

 

public synchronized static void init(){        ClassLoader cl = Thread.currentThread().getContextClassLoader();        Properties props = new Properties();        if(GlobalConstants.interfaceUrlProperties==null){            GlobalConstants.interfaceUrlProperties = new Properties();        }        InputStream in = null;        try {            in = cl.getResourceAsStream("interface_url.properties");            props.load(in);            for(Object key : props.keySet()){                GlobalConstants.interfaceUrlProperties.put(key, props.get(key));            }} catch (IOException e) {            e.printStackTrace();        }finally{            if(in!=null){                try {                    in.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }        return;    }



0 0
原创粉丝点击