欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Springboot 项目通过 Config ResourceBundle 类为静态方法和 config.properties 读取 yaml 配置文件信息。

最编程 2024-03-03 21:35:06
...

读取yaml 的配置文件

配置文件信息

iot_saas_tenement:
  user_id: 7........8d9b
  private_key: MII.......qQ==
  bj_url: http://4.....5:8088
  project_name: iot_s.......roject
  device_name: te.....ice

创建一个类 ProxyProperties 读取配置文件信息,并对外提供get方法

package com.purvardata.himp.third.bj.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

// 获取yaml的配置信息添加到静态方法
@Component
public final  class ProxyProperties {


    @Value("${iot_saas_tenement.bj_url}")
    private String bj_url;
    private static String url;

    @Value("${iot_saas_tenement.user_id}")
    private String user_id;
    private static String userId;

    @Value("${iot_saas_tenement.private_key}")
    private String private_key;
    private static String privateKey;

    @Value("${iot_saas_tenement.project_name}")
    private String project_name;
    private static String projectName;

    @Value("${iot_saas_tenement.device_name}")
    private String device_name;
    private static String deviceName;



    @PostConstruct
    public void setUrl() {
        url=this.bj_url;
        userId=this.user_id;
        privateKey=this.private_key;
        projectName=this.project_name;
        deviceName=this.device_name;
    }

    public static String getUrl() {
        return url;
    }

    public static String getUserId() {
        return userId;
    }

    public static String getPrivateKey() {
        return privateKey;
    }

    public static String getProjectName() {
        return projectName;
    }

    public static String getDeviceName() {
        return deviceName;
    }
}

目标静态方法通过get方法获取对应的属性

通过类 ResourceBundle 读取 config.properties 的配置文件

config.properties配置文件信息

userId=7dd.......9b
private_key=MIIC........Q==
url=http://4......5:8088
project_name=iot_sa..............ect

定义读取 配置类 PropertiesUtils,注意 config.properties 目录,要是和 ResourceBundle.getBundle("config")路径一致,我这里放根路径了

package com.iline.bj;

import java.util.ResourceBundle;

public class PropertiesUtils {


    private static ResourceBundle bundle = ResourceBundle.getBundle("config");

    /**
     * 获取值
     *
     * @param key
     * @return
     */
    public static String getValue(String key) {
        return bundle.getString(key);
    }

}

使用配置类 PropertiesUtils.getValue 获取配置文件 config.properties  的信息

推荐阅读