Spring Boot |超详细的SpringBoot配置及原理


Spring Boot的配置文件

1.全局配置文件

Spring Boot时,很多启动所需要的配置在底层都为我们默认配置好了,但是如果我们有对默认配置不满意的地方,我们就需要修改配置文件。在类路径下会有一个application.propertiesapplication.yml文件,这两个文件都会被Spring Boot当做全局配置文件。

  • 全局配置文件名字是固定的都是application,只是后缀有.properties.yml
  • 位置:src/main/resources目录或者类路径/config下。
  • 作用:修改Spring Boot自动配置的默认值。

2.yml介绍

以前的配置文件大多采用.xml的文件。YML(YAML Ain’t Markup Language)属于一种比较新型的文件,以数据为中心,比json、xml等更适合做配置文件。 另外Spring Boot使用 snakeyaml 解析yml文件。

比较一下为服务器更换端口号的写法:

<server>
	<port>8081<port>
</server>
server:
  port: 8081

可以明显的看到第二种yml版的比第一种xml版的更加简洁。

2.1yml基本语法

k:(空格)v:表示一对键值对。

  • 以空格的缩进来控制层级关系,只要是左边对齐的一列数据,都是同一个层级的。
  • 属性和值大小写敏感。
server:
  port: 8181
  path: /hello

2.1.1字面量

k:v

  • 数字、字符串、布尔、日期直接写
  • 字符串:默认不使用引号,可以使用单引号或者双引号,单引号原样输出,双引号会对特殊字符进行转义。字符串可以写成多行,从第二行开始,必须有一个单空格缩进。换行符会被转为空格。

2.1.2对象(Map)

对象的一组键值对和Map类似,使用冒号分隔。如:username: admin。

普通写法

friends:
   name: zhangsan
   age: 20

行内写法

friends: {name: lisi,age: 19}

2.1.3数组(list、set)

连词线(-)开头的行,构成一个数组,[]为行内写法。

普通写法

# 相当于var pets = [ 'cat','dog','pig'];
pets:
 - cat
 - dog
 - pig

行内写法

pets: [cat,dog,pig]

3.配置文件值注入

JavaBean组件

@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String name;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
	//省略setter、getter与toString方法
}

yml配置文件

person:
  name: 张三
  age: 18
  boss: false
  birth: 2020/1/13
  maps: {k1: v1,k2: v2}
  lists:
    - 李四
    - 王五
  dog:
    name: 旺旺
    age: 2

properties配置文件

person.name=张三
person.age=18
person.birth=2020/12/12
person.boss=false
person.maps.k1=v1
person.maps.k2=15
person.lists=a,b,c
person.dog.name=大黄
person.dog.age=3

想要使上面yml或properties中组件中的属性配置中的值一一绑定,需要在组件JavaBean中使用@ConfigurationProperties(prefix = "person")注解。

  • @ConfigurationProperties注解:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定,前提必须是容器中的组件。即需要先使用@Component将JavaBean加入到IoC容器中。

绑定时导入配置文件处理器,这样以后编写yml文件就有提示了:

	     <!--导入配置文件处理器-->
	      <dependency>
	          <groupId>org.springframework.boot</groupId>
	          <artifactId>spring-boot-configuration-processor</artifactId>
	          <optional>true</optional>
	      </dependency>

3.1配置properties配置文件时的编码问题

IDEA默认使用UTF-8编码,properties使用的是ASCII码,需要进行,编码转换:
在这里插入图片描述

3.2@ConfigurationProperties与@Value的区别

@Value的写法

    @Value("${person.name}")
    private String name;
    @Value("#{11*2}")
    private Integer age;
    @Value("true")
    private Boolean boss;
两者比较 @ConfigurationProperties @Value
功能 批量注入配配置文件中的属性 一个个指定
松散绑定(松散语法) 支持 不支持
SpEL 不支持 支持
JSR303数据校验 支持(需要添加@Validated注解) 不支持
复杂类型封装 支持 不支持

取舍问题:如果我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用@Value。如下

@RestController
public class HelloController {
    @Value("${person.name}")
    private String name;

    @RequestMapping("/say")
    public String sayHello() {
        return "Hello " + name;
    }
}

而如果专门写了一个JavaBean来和配置文件进行映射,使用@ConfigurationProperties。

3.3@PropertySource和@ImportResource

@PropertySource:加载指定的配置文件。

  • @ConfigurationProperties(prefix = "person")默认加载的是全局配置文件,使用@PropertySource(value = {"classpath:person.properties"})可以加载指定配置文件。

@ImportResource:导入Spring的配置文件,让配置文件生效。

  • Spring Boot中默认没有Spring的配置文件,想让Spring配置生效,需要使用此注解将Spring配置加载进来。
  • @ImportResource(locations = {"classpath:beans.xml"})

Spring Boot推荐的为容器中添加组件的方式是下面的全全注解的方式。

@Configuration
public class MyAppConfig {

    @Bean
    public HelloService helloService(){
        return new HelloService();
    }
}

4.配置文件随机数和占位符

配置文件中可以使用随机数:
${random.value}${random.int}${random.long}${random.int(10)}${random.int[1024,65546]}

占位符获取之前配置的值,如果没有可以使用默认值。

person.name=张三${random.uuid}
person.age=${random.int}
person.birth=2020/12/12
person.boss=false
person.maps.k1=v1
person.maps.k2=15
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog
person.dog.age=3

5.Profile

Profile是Spring用来做多环境支持的。可以通过激活、指定参数等方式快速切换环境。

5.1多profile形式

在主配置文件编写时,使用带这样的文件名:application-dev.propertiesapplication-prod.properties,可以实现动态的切换环境。

  • 当有多个主配置文件时,默认加载application.properties

5.2多profile文档块模式

server:
  port: 8081
spring:
  profiles:
    active: dev
---
server:
  port: 8082
spring:
  profiles: dev
---
server:
  port: 8083
spring:
  profiles: pro

5.3激活方式

(1)配置文件激活
使用spring.profiles.active=dev的方式进行激活。

(2)命令行激活
使用:--spring.profiles.active=dev
在这里插入图片描述
除了上述使用IDEA可视化工具来运行,还可以将项目打包成jar,使用java -jar spring-boot-02-config-0.0.1-SNAPSHOT.jar --spring.profoles.active=dev运行jar包的方式。

(3)JVM参数

虚拟机参数:–Dspring.profiles.active=dev
在这里插入图片描述

6.配置文件加载位置与顺序

springboot启动会扫描以下位置的application.properties或application.yml文件作为Spring Boot 的默认配置文件。
-file:./config/
-file:./
-classpath:/config/
-classpath:/
优先级由高到低,高优先级的配置会覆盖低优先级的配置。
Spring Boot会从这四个位置全部加载主配置文件,且互补配置。

除了应用内部,SpringBoot也可以从以下位置加载配置,优先级从高到低,高优先级的配置覆盖低优先级的配置,所有的配置会形成互补。

(1)命令行参数。
(2)来自java:comp/env的jndl属性。
(3)Java系统属性,(System.getProperties())。
(4)操作系统环境变量。
(5) RandomValuePropertySource配置的random.*属性值
(6) jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件。
(7) jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件。
(8) jar包外部的application.properties或application.yml(不带spring.profile)配置文件。
(9) jar包内部的application.properties或application.yml(不带spring.profile)配置文件。
(10) @Configuration注解类上的@PropertySource。
(11) 通过SpringApplication.setDefaultProperties指定的默认属性。

7.自动配置原理☆

①SpringBoot启动时会默认加载大量的自动配置类。
**②这些自动配置类中如果没有我们需要的组件,就需要在配置文件中指定这些属性的值。
③给容器中自动配置类添加组件时,会从properties类中获取某些属性。我们可以在配置文件中指定这些属性的值。

SpringBoot启动时,加载主配置类,开启了自动配置功能。@EnableAutoConfiguration注解的作用:利用@EnableAutoConfigurationImportSelector(选择器)为容器导入一些组件。

List<String> configurations = getCandidateConfigurations(annotationMetadata,
					attributes);//获取候选的配置
  • SpringFactoriesLoader.loadFactoryNames()
  • 扫描所有jar包类路径下的 META-INF/spring.factories文件。
  • 把扫描到的文件的内容包装成properties对象。
  • 从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中。

将类路径下META-INF/spring.factories里边配置的所有@EnableAutoConfiguration的值加入到容器中。

# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\
org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\
org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\
org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\
org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\
org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\
org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\
org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\
org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\
org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\
org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\
org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\
org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\
org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\
org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\
org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\
org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.OAuth2AutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,\
org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,\
org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,\
org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\
org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\
org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\
org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration

每一个xxxAutoConfiguration都是容器中的一个组件,用他们来做自动配置。

HttpEncodingAutoConfiguration为例解释自动配置原理:

@Configuration	//表示这是一个配置类,可以给容器中添加组件.

@EnableConfigurationProperties(HttpEncodingProperties.class)//启用指定类的EnableConfigurationProperties功能;
//将配置文件和对应的HttpEncodingAutoConfiguration绑定起来,并把HttpEncodingProperties加到IoC容器中

@ConditionalOnWebApplication//判断当前配置类是否是web应用,true(生效),false(不生效)

@ConditionalOnClass(CharacterEncodingFilter.class)//判断当前项目有没有这个类;
//CharacterEncodingFilter是SpringMVC中进行乱码解决的过滤器.

@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)//判断配置文件中是否存在某个配置spring.http.encoding.enabled;
//如果不存在,判断也是成立的.即使我们配置文件中不配置spring.http.encoding.enable=true,也是默认生效的.
public class HttpEncodingAutoConfiguration {
	//他已经和SpringBoot的配置文件映射了
	private final HttpEncodingProperties properties;
	//只有一个有参构造器的情况下,参数的值就会从容器中拿
	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
		this.properties = properties;
	}

	@Bean//为容器中添加一个组件,这个组件的某些值需要从properties中获取。
	@ConditionalOnMissingBean(CharacterEncodingFilter.class)
	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;
	}

根据不同的条件判断,决定这个配置类是否生效。一旦配置类生效,这个配置类就会为IoC容器中添加各种组件,这些组件的属性是从对应的properties类中获取的,这些类里面的属性又是和配置文件绑定的。所以我们能够手动配置的属性都是来自于某功能的properties类。

8.@Conditional注解和自动配置报告

8.1@Conditional派生注解

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

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

8.2自动配置报告

自动配置类必须在一定条件下才生效,如何才能知道哪些自动配置类生效哪些不生效呢?

可以在全局配置properties文件中通过debug=true属性,来让控制台打印自动配置报告。

在这里插入图片描述
在这里插入图片描述
通过这个属性,我们可以很方便的看到哪些自动配置启用了,哪些自动配置未启用。

发布了451 篇原创文章 · 获赞 1428 · 访问量 45万+

猜你喜欢

转载自blog.csdn.net/weixin_43691058/article/details/105166190