Java学习 — 获取配置文件信息

在实际微服务框架开发中,往往注册中心使用的是Nacos。当服务支持热部署后,在Nacos中修改配置,要可以被后端取到。所以在此提供一个简单获取配置的配置类:


import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Desc: 获取Nacos中配置信息
 * @Author: w_jin
 * @Data: 2025/7/23
 */
@Component
public class ApplicationContextProvider implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        applicationContext = context;
    }

    public static String getProperty(String key) {
        return applicationContext.getEnvironment().getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return applicationContext.getEnvironment().getProperty(key, defaultValue);
    }

    public static <T> T getProperty(String key, Class<T> targetType) {
        return applicationContext.getEnvironment().getProperty(key, targetType);
    }
}

可能是笔者自己的问题,使用过注解:@Value 等,获取的数据都存在问题。故使用配置类,方便调用。并将key值存在常量配置类中,完成分类

posted @ 2025-07-24 16:42  奋斗中de小伙有潜力  阅读(12)  评论(0)    收藏  举报