栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

2.读取动态拼接key的配置文件属性值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2.读取动态拼接key的配置文件属性值

0.要读取的配置文件

server:
  port: 8999

hc:
  test1: test1111
  test2: test2222

1.通过Environment读取

  @Autowired
    private Environment env;

    
    @RequestMapping("/read1")
    public String readYml1(int i) {
        String property = env.getProperty("hc.test"+i);
        return property;
    }

2.封装相关工具类

   
    @RequestMapping("/read")
    public String readYml(int i) {
        String property = EnvironmentUtil.getProperty("hc.test"+i);
        return property;
    }
import org.springframework.core.env.Environment;

public class EnvironmentUtil {
    public static Environment environment = SpringUtil.getBean(Environment.class);

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

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

@Component
public final class SpringUtil implements BeanFactoryPostProcessor {
    
    private static ConfigurableListableBeanFactory beanFactory;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtil.beanFactory = beanFactory;
    }
    
    public static  T getBean(Class clz) throws BeansException {
        T result = (T) beanFactory.getBean(clz);
        return result;
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/345083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号