application.properties
application.yml :标记语言,
配置文件的作用:修改Springboot的自动配置的默认值
YAML:是以数据为中心;
K:V:表示一对键值对(空格必须有)
以空格的缩进来控制层级关系;表示左对齐的一些列数据,都是同一等级的
属性和值也是大小写敏感;
K:V
字符串默认不加上单引号或者双引号
“ ”:双引号,不会转义字符串里面的特殊字符;特殊字符会作为本身表示的意思
name:“zhangsan \n lisi” :输出;zhangshan 换行 lisi
‘ ’:单引号,会转义特殊字符,特殊字符最终只是一个普通的字符串数据
name:‘zhangsan \n lisi’ :输出 zhangsan \n lisi
对象,Map(属性和值)(键值对)
k:v 在下一行来写对象的属性和值的关系;注意缩进
对象还是k:v的方式
friends:
lastName:zhangsan
age:20
friends: {lastName:"zhangsan",age:18}
数组
用 -值表述数组中的一个元素:
pets:
-cat
-dog
-pig
行内写法
pets:[cat,dog,pig]
一定要注意application.xml在resources文件夹中,
2.@Value 和ConfigurationProperties的区别
@Value和ConfigurationProperties(prefix="")的区别
ConfigurationProperties告诉Springboot将本类的所有属性和配置文件中的配置进行绑定
prefix配置文件中哪个下面的所有属性进行映射
@configurationProperties | @Value |
---|---|
功能 批量注入配置文件中的属性 | 一个一个指定 |
支持松散绑定 | 不支持 |
SPEL不支持 | 支持 |
JSR303数据校验 支持 | 不支持 |
校验数据需要再其中添加 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
如果再业务中需要获取配置文件中的某项值,使用@Value
如果我们专门编写一个javaBean来和配置文件进行映射,直接使用ConfigurationProperties;
3.@propertySource @ImportResource @Configuration
@propertySource加载指定的配置文件,例如创建另外一个yaml文件再类上添加注解
@ImportResource(locations = {“classpath:bean.xml”})
springboot中没有关于Spring的配置文件,我们自己再编写配置文件,也不能自动识别
需要@ImportResource标注再一个配置类上不是加在测试类上而是加在启动Application类上
@ImportResouce(locations = {"classpath:bean.xml"})
导入Spring的配置文件让其生效
Springboot推荐使用全注解的方式
通过@Configuration来配置全注解,并且再方法上添加@bean来配置将属性注册到容器中
4.随机数及占位符
随机数
${random.value} ${random.int},${random.long},${random.int(10),${random.int[1024,53336]}}
占位符
person.last-name = 张三${random.uuid}
persont.age = ${random.int}
person.dog.name = ${person.hello:hello_log}
5.profile
在配置文件中写application-{profile}.properties/yaml
默认使用的是application.yaml的配置
激活指定的profile
在配置文件中指定
spring:
profiles:
active: prod #指定属于哪个环境
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8086
spring:
profiles: dev
---
server:
port: 8084
spring:
profiles: prod
在命令行中添加–spring.profiles.active = dev
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-V07X3bny-1596094075272)(C:\Users\JYK\AppData\Roaming\Typora\typora-user-images\image-20200730091417356.png)]
--spring.profiles.active = dev
虚拟机参数:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DPqM1SxP-1596094075274)(C:\Users\JYK\AppData\Roaming\Typora\typora-user-images\image-20200730091309101.png)]
-Dpring.profiles.active=dev
或者在cmd中使用java -jar方式 xxx.jar --spring.profiles.active=dev
6配置文件加载位置
springboot启动扫描一i西安位置的application.yaml或者application.yml文件做为Springboot的默认配置文件
-file:./config/
-file:./
-classpath:/config/
-classpath:/
优先级由高到低,高优先级会覆盖低优先级
Springboot会从这四个位置全部加载配置文件:互补配置;
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UeQVD5xK-1596094075276)(C:\Users\JYK\AppData\Roaming\Typora\typora-user-images\image-20200730093138141.png)]
server:
port: 8083
servlet:
context-path: /say #指定访问地址
通过spring.config.location来改变默认配置
7外部配置加载顺序
从低到高优先级配置:所有配置会形成互补配置
1.命令行参数
2.来自java:comp/env的JNDI属性
3.Java系统属性(System.getProperties())
4.操作系统环境变量
5.RandomValuePropertySource配置的random.*属性值
由jar外向jar内进行寻找;
6.java包外部的application-{profile}.properties或application.yml{带spring.profile}配置文件
7.java包内部的application-{profile}.properties或application.yml{带spring.profile}配置文件
8.java包外部的application-{profile}.properties或application.yml{不带spring.profile}配置文件
9.java包内部的application-{profile}.properties或application.yml{不带spring.profile}配置文件
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-btg7MLbk-1596094075278)(C:\Users\JYK\AppData\Roaming\Typora\typora-user-images\image-20200730095957686.png)]
10.@Configuration注解类上加@PropertySource
11.通过SpringApplication.setDefaultProperties指定的默认属性
8.springboot的自动配置原理
自动配置原理
(1)SpringBoot启动的时候加载主配置类,开启自动配置功能@EnableAutoConfiguration
(2) @EnableAutoConfiguration作用:
(3)利用EnableAutoConfigurationSelector给容器导入一些组件
插件selectImports()方法的内容
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
//获取所有jar包类路径下 META-INF/spring.factories
把扫描到的文件内容包装成properties对象
从properties中获取EnableAutoConfiguration.class中对应的值,然后把他们加载到容器中
将类路径下的 META-INF/spring.factories中的配置所有的EnableAutoConfiguration的值加入到容器中
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.context.ConfigurationPropertiesAutoConfiguration,\
org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\
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.CassandraReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\
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.r2dbc.R2dbcDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\
org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\
org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\
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.ElasticsearchRestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\
org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\
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.http.HttpMessageConvertersAutoConfiguration,\
org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\
org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\
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.jersey.JerseyAutoConfiguration,\
org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\
org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\
org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\
org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\
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.mongo.embedded.EmbeddedMongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\
org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\
org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\
org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\
org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\
org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\
org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\
org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\
org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\
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.client.RestTemplateAutoConfiguration,\
org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\
org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\
org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\
org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
每一个这样的xxxAutoConfiguration类是容器中的一个组件,都加入到容器中;用他们来做自动配置
(4)每一个自动配置类进行自动配置功能
(5)以HttpEncodingAutoConfiguration为例
// 表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@Configuration(proxyBeanMethods = false)
//启动指定类的CongifurationProperties功能将配置文件中的对应的值和HttpEncodingProperties绑定起来;并把HttpEncodingProperties加入IOC容器中
@EnableConfigurationProperties(ServerProperties.class)
//Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类中的配置就会生效;判断当前应用是否是web应用,是的话配置类生效
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
//判断当前项目是否有这个类,CharacterEncodingFilter ;SpringMVC中进行乱码解决的过滤器
@ConditionalOnClass(CharacterEncodingFilter.class)
//判断配置文件中是否存在某一个配置,spring.http.encoding.enable;如果不存在,判断也是成立的,即使我们配置文件中不配置spring.http.encoding.enabled=true,也是默认生效的
@ConditionalOnProperty(prefix = "server.servlet.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {
//已经和springboot的配置文件映射了
private final Encoding properties;
//只有一个参数构造器的情况下,这个组件的某些值要从properties中获取
public HttpEncodingAutoConfiguration(ServerProperties properties) {
this.properties = properties.getServlet().getEncoding();
}
@Bean//给容器中添加一个组件,这个组件的某些值需要从properties中获取
@ConditionalOnMissingBean
public CharacterEncodingFilter characterEncodingFilter() {
CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter();
filter.setEncoding(this.properties.getCharset().name());
filter.setForceRequestEncoding(this.properties.shouldForce(Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(Encoding.Type.RESPONSE));
return filter;
}
根据当前不同的条件进行判断,决定这个配置类是否生效?
我们能配置的属性来源这个功能的properties这个类,一旦这个类生效,则类中的每一个属性都和配置文件进行绑定
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-mlUJ5AnS-1596094075279)(C:\Users\JYK\AppData\Roaming\Typora\typora-user-images\image-20200730111138751.png)]
SpringBoot的精髓:
- SpringBoot启动会加载大量的自动配置类
- 我们需要的功能有没有Springboot默认写好的自动配置类
- 再来看自动配置类中到底配置了哪些组件(有就不需要进行配置)
- 给容器中自动配置类中添加组件的时候,会从properties类中获取某些属性,就可以再配置文件中指定这些属性
xxxAutoConfiguration:自动配置类
给容器中添加组件
xxxProperties:封装配置文件中相关的属性
9.@Conditional派生注解(Spring注解原版中@Conditional作用)
作用:必须是@Conditional指定的条件成立,才会给容器中添加组件,配置类里面的内容才生效
@Condition扩展注解 | 作用(判断是否满足当前指定的条件) |
---|---|
@ConditionalOnJava | 系统的java版本是否满足要求 |
@ConditionalOnBean | 容器中存在指定Bean |
@ConditionalOnMissingBean | 容器中不存在指定的Bean |
@ConditionalOnExpression | 满足SpEL表单时 |
@ConditionalOnMissingClass | 系统中指定的类 |
@ConditionalOnSingleCandidate | 容器中只有一个指定的Bean,或者这个Bean是首选Bean |
@ConditionalOnProperties | 系统中指定的属性是否有指定的值 |
@ConditionalOnResource | 类路径下是否存在指定的资源文件 |
@ConditionalOnWebApplication | 当前的web环境 |
@ConditionalOnNotWebApplication | 当前不是web环境 |
@ConditionalOnJndi | JNDI存在指定项 |
自动配置类必须再一定的条件下才能生效
再yaml中添加debug=true,开启Springboot的debug模式
Positive matches:自动配置类,启动
Negative matches:自动配置类,没有启用