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

首先创建一个类 
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;
    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值