配置文件读取工具类

现在大部分配置文件读取方式都是需要注入的,这就导致静态方法调用特别麻烦,这里提供一个万能的配置文件读取方法:

一、配置文件(config.properties

config.name=XM
config.age=18

 二、配置文件读取工具类

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Properties;


@Component
public class ConfigUtil {

    private static Properties props ;

    //构造配置文件
    public ConfigUtil(){
        try {
            Resource resource = new ClassPathResource("config.properties");
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 获取属性
     * @param key
     * @return
     */
    public static String getProperty(String key){

        return props == null ? null :  props.getProperty(key);

    }

    /**
     * 获取属性
     * @param key 属性key
     * @param defaultValue 属性value
     * @return
     */
    public static String getProperty(String key,String defaultValue){

        return props == null ? null : props.getProperty(key, defaultValue);

    }

    /**
     * 获取properyies属性
     * @return
     */
    public static Properties getProperties(){
        return props;
    }
}

三、测试代码

    public static void main(String[] args) {
        //config.name的属性
        ConfigUtil.getProperty("config.name");
        //config.age的属性
       ConfigUtil.getProperty("config.age");
    }

 

posted @ 2020-12-18 14:20  想去天空的猫  阅读(170)  评论(0编辑  收藏  举报