maven项目,动态读取外部配置文件

需求

先说下我的需求,首先,我们的服务是个maven的项目,springboot,spring啥的统统都没有用,然后也不打算引入各种配置文件的jar,但是想要在程序运行中,可以动态的修改一些配置,并且程序能识别到,程序里读到的内容也实时变动。
废话不多说了,直接上代码!

代码

首先看一下不能实施的版本啥样
初版,能读到jar包配置文件

	private static final ResourceBundle resourceBundle;
    static{
        resourceBundle = ResourceBundle.getBundle("preprocessor-application");
    }
    public static String getKey(String key){
        ObjectMapper objectMapper = new ObjectMapper();
        String result=resourceBundle.getString(key);
        return result;
}

第二版,可以读到不打到jar包里的配置文件

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

public class ResourceUtil {
    private static final Logger logger = LoggerFactory.getLogger(ResourceUtil.class);

    /**
     * 属性文件全名
     */
    private static final String PFILE ="/home/conf/application.properties";
    /**
     * 对应于属性文件的文件对象变量
     */
    private static File m_file = null;
    /**
     * 属性文件的最后修改日期
     */
    private static long m_lastModifiedTime = 0;
    private static ResourceBundle rb;

    private static BufferedInputStream inputStream;
    static {
        try {
            m_file = new File(PFILE);
            m_lastModifiedTime = m_file.lastModified();
            inputStream = new BufferedInputStream(new FileInputStream(PFILE));
            rb = new PropertyResourceBundle(inputStream);
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static  String getKey(String key){
        long newTime = m_file.lastModified();
        if(newTime > m_lastModifiedTime){
            // Get rid of the old properties
            try {
                m_lastModifiedTime = m_file.lastModified();
                inputStream = new BufferedInputStream(new FileInputStream(PFILE));
                rb = new PropertyResourceBundle(inputStream);
                inputStream.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String result=rb.getString(key);
        
        return result;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盖丽男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值