zoukankan      html  css  js  c++  java
  • Spring中Environment的使用

    在Spring中当我们想拿到配置文件(不管是yml格式还是.properties格式)中的配置信息时,有很多种方式,采用Environment去获取是其中一种,优势是:

    • 可以通过getProperty这种比较通用的api来根据key获取value。
    • 当存在多份配置文件(比如SpringBoot应用jar包中有application.yml文件,外部也有application.yml文件),能取到生效的配置文件信息。

    一、使用示例如下(前提是在spring的应用中):

    package com.springDemodemo;
    
    import org.junit.jupiter.api.Test;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.core.env.Environment;
    
    @SpringBootTest
    public class EnvironmentTest {
    
        @Autowired
        Environment environment;
    
        @Test
        public void getProperty() {
            System.out.println(environment.getProperty("hello"));
        }
    
    }

    配置文件信息如下:

    hello=world

    打印结果如下:

    world

    二、封装为工具类

    package com.springDemodemo.utils;
    
    import org.springframework.core.env.Environment;
    
    public class EnvironmentUtil {
    
        public static Environment environment = SpringUtils.getBean(Environment.class);
    
        public static String getProperty(String key) {
            return environment.getProperty(key);
        }
    }

    用到的SpringUtils类如下:

    package com.springDemodemo.utils;
    
    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 SpringUtils implements BeanFactoryPostProcessor {
        /**
         * Spring应用上下文环境
         */
        private static ConfigurableListableBeanFactory beanFactory;
    
        @Override
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
            SpringUtils.beanFactory = beanFactory;
        }
    
    
        /**
         * 获取类型为requiredType的对象
         *
         * @param clz
         * @return
         * @throws BeansException
         */
        public static <T> T getBean(Class<T> clz) throws BeansException {
            T result = (T) beanFactory.getBean(clz);
            return result;
        }
    
    }
  • 相关阅读:
    PC客户端抓包方法(charles+proxifier)
    Charles分享
    python_fullstack数据库(一)-HTML
    python_fullstack数据库(三)-MySQL表操作
    python_fullstack数据库(二)-MySQL库操作
    python_fullstack数据库(一)-MySQL基本概念
    python_fullstack基础(十八)-并发编程
    python_fullstack基础(十七)-网络编程
    python_fullstack基础(十五)-面向对象三大特性
    python_fullstack基础(十四)-面向对象初识
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15101296.html
Copyright © 2011-2022 走看看