加载配置文件工具类

一、利用PropertiesConfiguration类加载配置文件

1、加载pom依赖


        <dependency>
            <groupId>commons-configurationgroupId>
            <artifactId>commons-configurationartifactId>
            <version>1.9version>
        dependency>


        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>

2、编写工具类

PropUtils.java

package com.zwt.utils.properties;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;

/**
 * 利用PropertiesConfiguration加载配置文件工具类
 */
public class PropUtils {
    private PropertiesConfiguration props = null;

    private static class LazyHolder {
        public static final PropUtils instance = new PropUtils();
    }

    public static PropUtils getInstance() {
        return LazyHolder.instance;
    }

    private PropUtils() {
        try {
            props = new PropertiesConfiguration("application.yml");
            props.setThrowExceptionOnMissing(true);
        } catch (ConfigurationException e) {
            throw new RuntimeException(String.format("Failed to load application.yml.[exception = %s]", e.getMessage()), e);
        }
    }

    public String getString(String key) {
        return props.getString(key);
    }

    public String getString(String key, String defaultValue) {
        return props.getString(key, defaultValue);
    }

    public int getInt(String key) {
        return props.getInt(key);
    }

    public int getInt(String key, int defaultValue) {
        return props.getInt(key, defaultValue);
    }

    public String[] getStringArray(String key) {
        return props.getStringArray(key);
    }

    public boolean getBoolean(String key, boolean defaultValue) {
        return props.getBoolean(key, defaultValue);
    }

    public short getShort(String key, Short defaultValue) {
        return props.getShort(key, defaultValue);
    }

    public Object getProperty(String key){
        return props.getProperty(key);
    }
}

3、配置文件新增配置

application.yml

##测试加载配置文件
#收件人列表
email.receivers: [email protected],[email protected]
#端口号
my.port: 9000
#是否运行
is.running: true
#用户名
user.name: jack
#店号
stores: 123,222,456

4、编写测试类

PropUtilsTest.java

package com.zwt.utils.properties;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;

/**
 * 测试加载配置文件配置内容
 */
@Slf4j
public class PropUtilsTest {

  // 邮件收件人列表
  private static String[] EMAIL_RECEIVERS;

  // 端口号
  private static int MY_PORT;

  // 是否运行
  private static Boolean IS_RUNNING;

  // 用户名称
  private static String USER_NAME;

  // 店号
  private static Integer[] STORES = new Integer[]{};


  // 静态代码块,加载配置文件内容
  static {
    try {
      PropUtils config = PropUtils.getInstance();

      EMAIL_RECEIVERS = config.getStringArray("email.receivers");
      // 如果配置文件没有,赋予默认值
      if (EMAIL_RECEIVERS == null || EMAIL_RECEIVERS.length == 0){
        EMAIL_RECEIVERS = new String[] { "[email protected]","[email protected]" };
      }
      // 如果配置文件没有,赋予默认值 8080
      MY_PORT = config.getInt("my.port", 8080);
      IS_RUNNING = config.getBoolean("is.running", false);
      USER_NAME = config.getString("user.name", "zhangsan");
      // 调用方法转换类型
      STORES = getStores();

    } catch (Exception e) {
      log.error("Can't read etl.properties", e);
    }
  }

  /**
   * 获取配置文件 stores 属性值
   * 并将 String数组 转换成 Integer数组
   * @return
   */
  private static Integer[] getStores() {
    String[] storeArray = PropUtils.getInstance().getStringArray("stores");

    if (ArrayUtils.isNotEmpty(storeArray)) {
      Integer[] stores = new Integer[storeArray.length];
      try {
        for (int i = 0; i < storeArray.length; i++) {
          stores[i] = Integer.parseInt(storeArray[i]);
        }
        return stores;
      } catch (NumberFormatException e) {
        log.error("Failed to parse stores, return empty array instead.[key = {}, value = {}]","stores", storeArray);
        return new Integer[0];
      }
    } else {
      return new Integer[]{};
    }
  }

  public static void main(String[] args) {
    // 收件人列表
    System.out.print("receiver:");
    for (String s:EMAIL_RECEIVERS) {
      System.out.print(s+" ");
    }
    System.out.println();

    // 端口号
    System.out.println("MY_PORT:"+ MY_PORT);

    // 是否运行
    System.out.println("IS_RUNNING:"+ IS_RUNNING);

    // 用户名称
    System.out.println("USER_NAME:"+ USER_NAME);

    // 店号
    System.out.print("store:");
    for (Integer s:STORES) {
      System.out.print(s+" ");
    }
    System.out.println();
  }

}

5、测试运行

加载配置文件工具类_第1张图片

二、利用 Props类 加载配置文件

1、加载pom依赖


        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.6.0version>
        dependency>

2、配置文件新增配置

application.yml

##测试加载配置文件
#用户名
user.name: jack

3、编写测试类

HutoolPropsTest.java

package com.zwt.utils.properties;

import cn.hutool.setting.dialect.Props;

/**
 * 利用 hutool-setting 加载配置文件
 */
public class HutoolPropsTest {

  /**
   * hutool-setting	功能更强大的Setting配置文件和Properties封装
   */
  protected static Props props;

  // 用户名称
  private static String USER_NAME;

  static {
    // 加载配置文件
    props = new Props("application.yml");
    // 获取配置文件user.name属性值,为空则赋默认值
    USER_NAME = props.getProperty("user.name","默认名称");
  ;
  }

  public static void main(String[] args) {
    System.out.println("用户名:"+USER_NAME);
  }

}

4、测试运行

在这里插入图片描述

你可能感兴趣的:(Java,SE,JavaWeb,java,加载配置文件)