SpringBoot获取不到application.properties的值

导读

  最近在搭建消息网关服务,因为里面用到了设计模式,启动的时候,没有被Spring管理到,使用@Value(${})迟迟获取不到application.properties里的值,然后手写一个工具类,其他地方调用的时候,只需要从工具类中获取key即可。

工具类

package com.ybchen.smsgateway.config;

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;

/**
 * @ClassName:SystemConfig
 * @Description:系统配置类
 * @Author:chenyb
 * @Date:2020/12/2 4:11 下午
 * @Versiion:1.0
 */
@Component
public class SystemConfig {
    private static Properties props ;
    public SystemConfig(){
        try {
            Resource resource = new ClassPathResource("/application.properties"); //读取那个配置文件
            props = PropertiesLoaderUtils.loadProperties(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String getProperty(String key){

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

    }
    public static String getProperty(String key,String defaultValue){

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

    }
    public static Properties getProperties(){
        return props;
    }
}

调用

SystemConfig.getProperty("wx.appID")

原文地址:https://www.cnblogs.com/chenyanbin/p/14074494.html