Properties配置文件装载进JavaBean对象工具函数

546 阅读1分钟

前言

本文所用Properties配置读取使用的commons-configuration2
pom.xml引入:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-configuration2</artifactId>
    <version>2.4</version>
</dependency>

正文

先练个手,读取配置文件字段和值进HashMap。

/**
 * @desc 加载properties配置文件到Map
 * @param propertiesPath
 * @return
 */
public static HashMap<String, String> loadConfig(String propertiesPath) throws Exception{
    if (propertiesPath == null || propertiesPath.length() == 0) {
        return null;
    }
    PropertiesConfiguration config = new Configurations().properties(propertiesPath);
    if (config.size() == 0) return null;
    HashMap<String, String> configMap = new HashMap<>();
    for (Iterator<String> iterator = config.getKeys(); iterator.hasNext();)
    {
        String key = iterator.next();
        String value = config.getString(key);
        if (value == null || value.length() == 0) {
            return null;
        }
        configMap.put(key, value);
    }
    return configMap;
}

使用java反射机制,实例化一个对象,并把Properties配置文件的属性和值赋值给对象。

/**
 * @desc 加载properties配置文件到范型对象
 * @param cls 范型对象Class
 * @param propertiesPath 文件地址
 * @param <T>
 * @return
 * @throws Exception
 */
public static <T> T loadConfigBean(Class<T> cls, String propertiesPath) throws Exception{
    if (propertiesPath == null || propertiesPath.length() == 0) {
        return null;
    }
    PropertiesConfiguration configuration = new Configurations().properties(propertiesPath);
    if (configuration.size() == 0) return null;
    T t = (T) cls.newInstance();
    Field[] fields = t.getClass().getDeclaredFields();
    for (Field field:fields) {
        field.setAccessible(true);
        Object value = configuration.get(field.getType(), field.getName());
        //获取不到的字段自动忽略
        if (value == null) {
            System.out.println(field.getType() + " " + field.getName() + "get configuration is null");
            continue;
        }
        field.set(t, value);
    }
    return t;
}