當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring中Environment的使用
生活随笔
收集整理的這篇文章主要介紹了
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 {@AutowiredEnvironment environment;@Testpublic 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;@Overridepublic 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;}}總結
以上是生活随笔為你收集整理的Spring中Environment的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 机器人操作空间轨迹规划 -- 姿态规划
- 下一篇: 人工智能文本生成器将如何影响写作行业