spring Environment上下文环境参数变量

2023-10-21 15:44

本文主要是介绍spring Environment上下文环境参数变量,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

spring通过Environment对象来存储上下文环境变量信息,即包含当前系统环境变量也包含配置文件配置变量。Environment作为一个bean被存放在容器中,可以在需要的地方进行依赖注入直接使用。

Environment的创建

以AnnotationConfigApplicationContext容器类来看,在其构造函数总会初始化reader = new AnnotatedBeanDefinitionReader(this);然后会调用重载构造函数AnnotatedBeanDefinitionReader(registry, getOrCreateEnvironment(registry)),最后通过getEnvironment获取environment。

AbstractApplicationContext#getEnvironment

public ConfigurableEnvironment getEnvironment() {if (this.environment == null) {this.environment = createEnvironment();}return this.environment;
}protected ConfigurableEnvironment createEnvironment() {return new StandardEnvironment();}

这里最后看到创建了一个StandardEnvironment类型的实例。

Environment放入容器

在使用中,可以直接通过注解注入的方式将environment注入直接使用,如下:

@Autowired
private Environment env;

那么environment什么时候装载到容器中,成为一个bean的呢?

这里还要回到容器初始化的Refresh方法,在初始化扫描到的bean前,会调用prepareBeanFactory()方法。

AbstractApplicationContext#prepareBeanFactory

//...
// Register default environment beans.
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
}

这一步发生在所有的bean实例化之前,beanFactory.registerSingleton方法会将当前对象放到容器单例池里。也就是单例bean。可以说上面几个bean是最早一批bean。这里看到有environment、systemProperties、systemEnvironment和applicationStartup。

属性文件加载

在上一篇文章中介绍@Configuration时候可以通过@PropertySource进行属性配置文件的引入,引入的配置文件最终会放入environment中,可以通过environment对象获取属性文件内容。

如下:

    @Autowiredprivate Environment env;@PostConstructpublic void init(){log.info("property name:{}",env.getProperty("name"));}

那么配置文件是怎么被存放到environment中的呢?在上面一步将environment放入spring容器的一步,所有的bean都还未实例化,@PropertySource也未初始化,这时候还未加载自定义引入的properties配置文件。

还是上一篇文章说的,容器会引入ConfigurationClassPostProcessor类来解析处理@Configuration注解,该类

不仅是一个bean定义后置处理器,还继承了EnvironmentAware接口。这样当ConfigurationClassPostProcessor在被容器实例化的时候,initializeBean()方法会调用invokeAwareInterfaces方法,这里会调到setEnvironment方法将容器的environment传递给当前ConfigurationClassPostProcessor。这样ConfigurationClassPostProcessor就拥有了容器的environment。

ApplicationContextAwareProcessor#invokeAwareInterfaces

private void invokeAwareInterfaces(Object bean) {if (bean instanceof EnvironmentAware) {((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());}//...
}

下一步在ApplicationContextAwareProcessor中会使用ConfigurationClassParser类进行@PropertySource的解析,将解析到的property追加到environment的propertySources中。

具体逻辑在ConfigurationClassParser#addPropertySource()中。

最后来看下environment内部存储结构吧:

{//存储Profileprivate final Set<String> activeProfiles = new LinkedHashSet<>();private final Set<String> defaultProfiles = new LinkedHashSet<>(getReservedDefaultProfiles());//内部使用List<PropertySource<?>> propertySourceList来存储多个PropertySourceprivate final MutablePropertySources propertySources;private final ConfigurablePropertyResolver propertyResolver;
}

Profile怎么理解呢,可以理成剖面,环境。举例说明就好理解了。

bean可以通过@Profile进行修饰,例如在数据源datasources初始化时候可以指定不同的Profile。

@Profile("dev")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource getDuridSource(){return new DruidDataSource();
}
@Profile("sit")
@ConfigurationProperties(prefix="spring.datasource")
public DataSource getDuridSource(){return new DruidDataSource();
}

如果一个bean被@Profile修饰,则只有当只有@Profile指定的值在activeProfiles之内,bean才会被加载。

profile的取值设定在

AbstractEnvironment#doGetActiveProfiles

protected Set<String> doGetActiveProfiles() {synchronized (this.activeProfiles) {if (this.activeProfiles.isEmpty()) {String profiles = doGetActiveProfilesProperty();if (StringUtils.hasText(profiles)) {setActiveProfiles(StringUtils.commaDelimitedListToStringArray(StringUtils.trimAllWhitespace(profiles)));}}return this.activeProfiles;}
}protected String doGetActiveProfilesProperty() {return getProperty(ACTIVE_PROFILES_PROPERTY_NAME);}

这里ACTIVE_PROFILES_PROPERTY_NAME = “spring.profiles.active"。可以在启动时候通过-Dspring.profiles.active=xx来指定,也可以配置到properties文件中。都可以解析的到。

这篇关于spring Environment上下文环境参数变量的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/255365

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

创建Java keystore文件的完整指南及详细步骤

《创建Javakeystore文件的完整指南及详细步骤》本文详解Java中keystore的创建与配置,涵盖私钥管理、自签名与CA证书生成、SSL/TLS应用,强调安全存储及验证机制,确保通信加密和... 目录1. 秘密键(私钥)的理解与管理私钥的定义与重要性私钥的管理策略私钥的生成与存储2. 证书的创建与

浅析Spring如何控制Bean的加载顺序

《浅析Spring如何控制Bean的加载顺序》在大多数情况下,我们不需要手动控制Bean的加载顺序,因为Spring的IoC容器足够智能,但在某些特殊场景下,这种隐式的依赖关系可能不存在,下面我们就来... 目录核心原则:依赖驱动加载手动控制 Bean 加载顺序的方法方法 1:使用@DependsOn(最直

SpringBoot中如何使用Assert进行断言校验

《SpringBoot中如何使用Assert进行断言校验》Java提供了内置的assert机制,而Spring框架也提供了更强大的Assert工具类来帮助开发者进行参数校验和状态检查,下... 目录前言一、Java 原生assert简介1.1 使用方式1.2 示例代码1.3 优缺点分析二、Spring Fr

java使用protobuf-maven-plugin的插件编译proto文件详解

《java使用protobuf-maven-plugin的插件编译proto文件详解》:本文主要介绍java使用protobuf-maven-plugin的插件编译proto文件,具有很好的参考价... 目录protobuf文件作为数据传输和存储的协议主要介绍在Java使用maven编译proto文件的插件