Java不使用依赖注入获取配置文件新

JAVA获取配置文件

大部分Java应用程序可以使用依赖注入的方式再通过@Value获取配置文件中的值,但是有些功能没办法进行依赖注入

不用依赖注入获取配置文件

导入maven配置文件,该工具可以更好的获取配置文件

<dependency>
   <groupId>com.typesafe</groupId>
   <artifactId>config</artifactId>
   <version>1.2.0</version>
</dependency>

工具代码类

package com.clear.zhfw.bus.utils;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigParseOptions;
import com.typesafe.config.ConfigSyntax;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

/**
 * @author 嘟嘟嘟
 * @date 2023年04月17日
 **/
@Slf4j
public class AppConfigUtil {
    // 获取jar包运行时指定配置文件路径的地址,即-Dspring.config.location地址
    // java jar -Dspring.config.location=D:\test\config\ "test.jar"
    private static final String CONFIG_FILE = System.getProperty("spring.config.location");

    private static final Config config = loadConfig();

    private AppConfigUtil() {
    }

    private static Config loadConfig() {
        log.info("加载到的配置文件路径为:{}", CONFIG_FILE);
        if (CONFIG_FILE != null) {

            Config config = getConfigByFile(CONFIG_FILE + "application.properties");

            String active = config.getString("spring.profiles.active");

            Config activeConfig = getConfigByFile(CONFIG_FILE + "application-" + active + ".properties");
            config = config.withFallback(activeConfig);

            return config;

        } else {

            Config config = getConfigByActive("application.properties");

            String active = config.getString("spring.profiles.active");

            Config activeConfig = getConfigByActive("application-" + active + ".properties");
            config = config.withFallback(activeConfig);


            return config;
        }
    }

    public static String getProperty(String key) {
        return config.getString(key);
    }

    private static Config getConfigByActive(String pre) {
        return ConfigFactory.parseResources(pre, ConfigParseOptions.defaults().setSyntax(ConfigSyntax.PROPERTIES));
    }

    private static Config getConfigByFile(String fileUrl) {
        return ConfigFactory.parseFile(new File(fileUrl));
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值