一、SpringBoot 多环境配置文件

  Profile 是 Spring 对不同环境提供不同配置功能的支持,可以通过激活指定参数等方式快速切换环境。

1、多 profile 文件形式

  格式:application-{profile}.yml

  • application-dev.yml
  • application-prod.yml
2、多 profile 文档块模式

   多 profile 文档块模式仅限于 yml 文件,下面的例子,项目启动后运行的是 8082 端口。

server:
  port: 8081
spring:
  profiles:
    active: dev
---
server:
  port: 8082
spring:
  # 指定属于哪个环境
  profiles: dev

---
server:
  port: 8083
spring:
  profiles: prod
3、激活方式
  • 命令行 --spring.profiles.active=dev
  • 配置文件 spring.profiles.active=dev
  • jvm 参数 -Dspring.profiles.active=dev

  在 idea 中配置命令行和 jvm 参数。

image.png

二、多配置文件

1、配置文件的加载位置

  SpringBoot 启动会扫描以下位置的 application.properties 或者 application.yml 文件作为 SpringBoot 的默认配置文件。

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/

image.png

  以上是按照优先级从高到底的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置的内容。

2、加载指定配置文件

  我们也可以通过配置 spring.config.location 来 加载指定配置文件,将项目打成 jar 包,通过命令行参数修改 spring.config.location 属性值。

Java -jar 2.jar --spring.config.location=C:\Users\HP\Desktop\文档\application.yml
3、外部配置文件的加载顺序

  SpringBoot 支持多种外部配置方式,SpringBoot 也可以从以下位置加载配置,优先级从高到底,高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置,官网提供了 17 种方式(官网链接)

  1. 命令行参数,--配置项=值;例如 java -jar springboot.jar --server.port=8087 多个配置用空格分开。
  2. 来着 java:comp/env 的 NDI 属性
  3. Java 系统属性(System.getProperties())
  4. 操作系统环境变量
  5. RandomValuePropertySource 配置的 random.* 属性值
  6. jar 包外部的 application-{profile}.yml 的配置文件
  7. jar 包内部的 application-{profile}.yml 的配置文件
  8. jar 包外部的 application.yml 的配置文件
  9. jar 包内部的 application.yml 的配置文件
  10. @Configuration 注解类上的 @PropertySource
  11. 通过 SpringApplication.setDefaultProperties 制定默认配置

三、自动配置原理

  SpringBoot 启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration

1、@EnableAutoConfiguration 的作用:
  • 利用 AutoConfigurationImportSelector.class 给容器中导入一些组件,可以查看 selectImports() 方法的内容。
  • 通过 List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes); 获取候选的配置。
  • 通过 SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),getBeanClassLoader()); 扫描所有 jar 包类路径下 META-INF/spring.factories 把扫描到的这些文件的内容包装成 properties 对象,从 properties 中获取到 EnableAutoConfiguration.class 对应的值,然后把它们添加在容器中。

  将 类路径下 META-INF/spring.factories 里面配置的所有 EnableAutoConfiguration 的值加入到了容器中,如图:

image.png

  每一个这样的 xxxAutoConfiguration 类都是容器中的一个组件,都会加入到容器中,用它们来做自动配置,每一个自动配置类进行自动配置的功能。

2、HttpEncodingAutoConfiguration 自动配置原理

  以 HttpEncodingAutoConfiguration 类以例,解释自动配置原理。

// 表示这是一个配置类,和以前编写的配置文件一样,可以给容器中添加组件
@Configuration(proxyBeanMethods = false)
// 启动指定类的 ConfigurationProperties 功能,将配置文件中对应的值和 HttpProperties 绑定起来,并把 HttpProperties 加入到 IOC 容器中
@EnableConfigurationProperties(HttpProperties.class)
// Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效。当前注解的作用:判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
// 判断当前项目有没有 CharacterEncodingFilter 这个类。CharacterEncodingFilter是SpringMVC中进行乱码解决的过滤器
@ConditionalOnClass(CharacterEncodingFilter.class)
// 判断配置文件中是否存在某个配置 spring.http.encoding ,默认为 true
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {
	// 它已经和SpringBoot的配置文件映射了
	private final HttpProperties.Encoding properties;
	// 只有一个有参构造器的情况下,参数的值就会从容器中拿
	public HttpEncodingAutoConfiguration(HttpProperties properties) {
		this.properties = properties.getEncoding();
	}

	// 给容器中添加一个组件,这个组件的某些值需要从properties中获取
	@Bean
	@ConditionalOnMissingBean
	public CharacterEncodingFilter characterEncodingFilter() {
		CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
		filter.setEncoding(this.properties.getCharset().name());
		filter.setForceRequestEncoding(this.properties.shouldForce(Type.REQUEST));
		filter.setForceResponseEncoding(this.properties.shouldForce(Type.RESPONSE));
		return filter;
	}

  根据当前不同的条件判断,决定这个配置类是否生效。一但这个配置类生效,这个配置类就会给容器中添加各种组件,这些组件的属性是从对应的 properties 类中获取的,这些类里面的每一个属性又是和配置文件绑定的。

  所有在配置文件中能配置的属性都在 xxxProperties 类中封装着,配置文件的配置属性就参考这个属性类。

// 从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(prefix = "spring.http")
public class HttpProperties {
3、总结
  1. SpringBoot 启动时会加载大量的自动配置类。
  2. 我们看我们需要的功能有没有被 SpringBoot 自动配置好。
  3. 我们再来看这个自动配置类中到底配置了哪些组件(只要我们要用的组件有,我们就不需要来配置)。
  4. 给容器中自动配置类添加组件的时候,会从 properties 类中获取某些属性。我们就可以在配置文件中指定这写属性的值。
  5. xxxAutoConfigurartion:自动配置类,给容器中添加组件。
  6. xxxProperties:封装配置文件相关属性:

四、@Conditional 派生注解

  @Conditional 派生注解的作用是:当 @Conditional 指定的条件成立,才给容器中添加组件,配置中的所有内容才生效。

@Conditional 扩展注解作用(判断是否满足当前指定条件)
@ConditionalOnJava系统的 Java 版本是否符合要求
@ConditionalOnBean容器中存在指定 Bean
@ConditionalOnMissingBean容器中不存在指定 Bean
@ConditionalOnExpression满足指定 SpEL 表达式
@ConditionalOnClass系统中有指定的类
@ConditionalOnMissingClass系统中没有指定的类
@ConditionalOnSingleCandidate容器中只有一个指定的 Bean,或者这个 Bean 是首选 Bean
@ConditionalOnProperty系统中指定的属性是否有指定的值
@ConditionalOnResource类路径下是否存在指定资源文件
@ConditionalOnWebApplication当前是 Web 环境
@ConditionalOnNotWebApplication当前环境不是 Web 环境
@ConditionalOnJndiJNDI 存在指定项
SpringBoot 的 debug 模式

  我们如何知道哪些自动配置类生效,可以通过启动 SpringBoot 的 debug 模式,来让控制台打印自动配置报告,这样我们就可以很方便的知道哪些自动配置类生效。

  直接在 SpringBoot 的配置文件中配置 debug: true ,启动项目后,控制台会输出一下信息

============================
CONDITIONS EVALUATION REPORT
============================


Positive matches: (自动配置类启动的)
-----------------

   AopAutoConfiguration matched:
      - @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)

   AopAutoConfiguration.ClassProxyingConfiguration matched:
      - @ConditionalOnMissingClass did not find unwanted class 'org.aspectj.weaver.Advice' (OnClassCondition)
      - @ConditionalOnProperty (spring.aop.proxy-target-class=true) matched (OnPropertyCondition)

   DispatcherServletAutoConfiguration matched:
      - @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet' (OnClassCondition)
      - found 'session' scope (OnWebApplicationCondition)
...

Negative matches: (自动配置类没启动的,没有匹配成功)
-----------------

   ActiveMQAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)

   AopAutoConfiguration.AspectJAutoProxyingConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.aspectj.weaver.Advice' (OnClassCondition)

   ArtemisAutoConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory' (OnClassCondition)

标题:SpringBoot 的多配置文件以及自动配置原理
作者:Yi-Xing
地址:http://47.94.239.232:10014/articles/2020/03/29/1585493496197.html
博客中若有不恰当的地方,请您一定要告诉我。前路崎岖,望我们可以互相帮助,并肩前行!