zoukankan      html  css  js  c++  java
  • 不停服务,动态加载properties资源文件

    系统运行过程中,我们用注解@Value("${****}")可以获取资源文件中的内

    容,获取的内容会被存储在spring缓存中,因此如果我们修改了资源文件,要

    想读取到修改后的内容,那就必须重启服务才能生效。那么如果想修改资源文

    件中的内容,又不想重启服务,那么只能让服务动态加载资源文件,每一次读

    取都是最新的内容,不去读缓存,解决方式如下:

    利用工具读取资源文件

    package com.***.**.utils;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import com.sinoway.cisp.controller.ApiController;
    
    /**
     * 获取properties文件内容工具类
     */
    public class PropertyUtil {
    
        private final static Logger logger = LoggerFactory.getLogger(ApiController.class);
    
        public static String getProperty(String key) {
            Properties props = new Properties();
            InputStream in = null;
            String property = null;
            try {
                // 第一种,通过类加载器进行获取properties文件流
                // in = PropertyUtil.class.getClassLoader().getResourceAsStream("Constant.properties");
                // 第二种,通过绝对路径进行获取properties文件流
                String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
                in = new FileInputStream(path + "/Constant.properties");
                props.load(in);
    
                property = props.getProperty(key);
            } catch (FileNotFoundException e) {
                logger.error("Constant.properties文件未找到");
            } catch (IOException e) {
                logger.error("出现IOException");
            } finally {
                try {
                    if (null != in) {
                        in.close();
                    }
                } catch (IOException e) {
                    logger.error("文件流关闭出现异常");
                }
            }
            logger.info("加载资源文件完成...........");
            logger.info("文件内容为:" + props);
            return property;
        }
    }

    通过工具获取资源文件中的内容,是每次都会重新读取的,以此来达到动态加载资源文件的目的

  • 相关阅读:
    audio元素
    获取页面中出现次数最多的三个标签以及出现次数
    vue ssr(server side rendering)
    python_2 python的编码声明
    python_1 python的编译过程
    bugs
    isPrototypeOf和 instanceof 的区别
    WebStorm 配置Git
    MongoDB 副本集搭建
    获取结算样式 getComputedStyle-currentStyle
  • 原文地址:https://www.cnblogs.com/java-spring/p/9621700.html
Copyright © 2011-2022 走看看