SpringBoot配置文件(2)
六、配置文件加载
SpringBoot 启动会扫描以下位置的application.properties或者application.yml文件作为SpringBoot的默认配置文件
- file:./config/
- file: ./
- classpath: /config/
- classpath: /
- 以上按照访问优先级从高到底的顺序,将所有位置的文件都会被加载,高优先级的配置会覆盖掉低优先级的内容
- 我们也可以通过配置spring.config.location来改变默认配置。
七、外部配置加载顺序
SpringBoot也可以从以下位置加载配置;优先级从高到低;高优先级的配置覆盖低优先级的配置,所有配置之间互补。
命令行参数
java -jar xxx.jar --server.servlet.context-path=/hello --server.port=8081
多个配置参数之间用空格分开 --配置项=值
需要注意的是在SpringBoot1.0-2.0时配置路径的参数是server.context-path; 现在都是2.0往上了所以需要改成server.servlet.context-path来自java:comp/env的JNDI属性
Java系统属性
操作系统环境变量
RandomValuePropertySource配置的random.*属性
jar包外部的application-profile.properties或application.yml 这些是带上spring.profile配置文件
jar包内部的application-profile.properties或application.yml 这些是带spring.profile配置文件
jar包外部的application-profile.properties或application.yml
jar包内部的application-profile.properties或application.yml
有jar包外的配置文件先加载外面的再加载里面的,如果是profile文件先加载带profile字段的配置文件@Configuration注解类上的@PropertySource
通过SpringApplication.setDefaultProperties指定的默认属性
八、自动配置原理
自动配置原理:
SpringBoot启动时会加载主配置类,开启了自动配置功能@EnableAutoConfiguration
@EnableAutoConfiguration的作用:
- 利用AutoConfigurationImportSelector给IOC容器中导入一些组件
- 可以查看AutoConfigurationImportSelector类中selectImports方法
- 其中在getAutoConfigurationEntry方法中的
List<String> configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
SpringFactoriesLoader.loadFactoryNames()
这个方法会扫描所有jar包类路径下META/spring.factories文件他把扫描到的这些文件的内容封装成properties对象,从properties中获取到EnableAutoConfiguration.class类对应的值然后把它添加到容器中
将类路径下META/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.CloudServiceConnectorsAutoConfiguration,\
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.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.ElasticsearchAutoConfiguration,\
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.ReactiveRestClientAutoConfiguration,\
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.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.jest.JestAutoConfiguration,\
org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration,\
org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\
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.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.groovy.template.GroovyTemplateAutoConfiguration,\
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.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.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
每个自动配置类都会进行自动配置功能
以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理
@Configuration(
//表示是一个配置类,以前编写的配置文件一样,可以给容器中添加组件
proxyBeanMethods = false
)
@EnableConfigurationProperties({HttpProperties.class})
//启动HttpProperties属性类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingProperties绑定起来
@ConditionalOnWebApplication(
//判断当前应用是否是Web应用,如果是,配置类才会起作用
type = Type.SERVLET
)
//ConditionalOnClass判断当前项目中是否含有CharacterEncodingFilter类;
//并把CharacterEncodingFilter类加载到IOC容器中。
@ConditionalOnClass({CharacterEncodingFilter.class})
@ConditionalOnProperty(
//判断当前项目中是否含有spring.http.encoding.enabled属性,
// matchIfMissing = true即使没有这个属性也会返回true,也是生效的
prefix = "spring.http.encoding",
value = {"enabled"},
matchIfMissing = true
)
public class HttpEncodingAutoConfiguration {
private final Encoding properties;
根据当前不同条件的判断,决定这个配置类是否生效?如果生效,这个配置类会与IOC容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,而properties类里面的属性有事和SpringBoot配置文件中的属性绑定的。
重点:
- SpringBoot启动会加载大量的自动配置类
- 我们在SpringBoot默认写好的自动配置类中查看有没有与我们想要的功能的组件
- 如果有我们就不需要再配置了
- 如果没有我们可以在配置文件中指定这些属性的值,因为IOC容器添加组件的时候,会从properties类中获取某些属性,而xxxProperties类中的属性获取又是和我们写的配置文件中的属性绑定在一起的。
@Conditional派生注解
查看@Conditional注解的源码实现
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Conditional {
Class<? extends Condition>[] value();
}
这玩意儿继承了Condition,Condition接口是Spring4中的条件接口,需要实现matches方法,返回值是boolean类型.
public interface Condition {
boolean matches(ConditionContext var1, AnnotatedTypeMetadata var2);
}
我们查看SpringBootCondition这个抽象类的结构
public abstract class SpringBootCondition implements Condition {
private final Log logger = LogFactory.getLog(this.getClass());
public SpringBootCondition() {
}
public final boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String classOrMethodName = getClassOrMethodName(metadata);
try {
ConditionOutcome outcome = this.getMatchOutcome(context, metadata);
this.logOutcome(classOrMethodName, outcome);
this.recordEvaluation(context, classOrMethodName, outcome);
return outcome.isMatch();
} catch (NoClassDefFoundError var5) {
throw new IllegalStateException("Could not evaluate condition on " + classOrMethodName + " due to " + var5.getMessage() + " not found. Make sure your own configuration does not rely on that class. This can also happen if you are @ComponentScanning a springframework package (e.g. if you put a @ComponentScan in the default package by mistake)", var5);
} catch (RuntimeException var6) {
throw new IllegalStateException("Error processing condition on " + this.getName(metadata), var6);
}
}
原来下面的派生注解都是继承了SpringBootCondition,而SpringBootCondition又实现类Condition接口,重写了matches方法。
- @Conditional派生注解 作用(都是判断是否符合指定的条件)
- @ConditionalOnJava 系统的java版本是否符合要求
- @ConditionalOnBean 有指定的Bean类
- @ConditionalOnMissingBean 没有指定的bean类
- @ConditionalOnExpression 符合指定的SpEL表达式
- @ConditionalOnClass 有指定的类
- @ConditionalOnMissingClass 没有指定的类
- @ConditionalOnSingleCandidate 容器只有一个指定的bean,或者这个bean是首选bean
- @ConditionalOnProperty 指定的property属性有指定的值
- @ConditionalOnResource 路径下存在指定的资源
- @ConditionalOnWebApplication 系统环境是web环境
- @ConditionalOnNotWebApplication 系统环境不是web环境
- @ConditionalOnjndi JNDI存在指定的项
既然自动配置类必须在一定的条件下才能生效(也就是matches方法返回true)那么我们怎么知道到底哪些自动配置类生效,哪些没有生效?
解决方法:我们可以启用debug模式,让控制台打印哪些配置类生效哪些没有。
在application.yml/properties中设置 debug:true;/ debug=true(任意一处设置即可)
控制台输出内容:
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches://已经匹配的配置类
AopAutoConfiguration matched:
- @ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)
…
Negative matches://没有生效的配置类
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class ‘javax.jms.ConnectionFactory’ (OnClassCondition)
这样我们就可以知道哪些配置类生效,哪些没有。
初学菜鸟,以上有不足之处敬请指出!
SpringBoot配置文件(2)的更多相关文章
- 解决spring-boot配置文件使用加密方式保存敏感数据启动报错No decryption for FailsafeTextEncryptor. Did you configure the keystore correctly
spring-boot配置文件使用加密方式保存敏感数据 application.yml spring: datasource: username: dbuser password: '{cipher} ...
- springboot配置文件中使用当前配置的变量
在开发中,有时我们的application.properties某些值需要重复使用,比如配置redis和数据库或者mongodb连接地址,日志,文件上传地址等,且这些地址如果都是相同或者父路径是相同的 ...
- SpringBoot 配置文件存放位置及读取顺序
SpringBoot配置文件可以使用yml格式和properties格式 分别的默认命名为:application.yml.application.properties 存放目录 SpringBoot ...
- [SpringBoot] - 配置文件的多种形式及JSR303数据校验
Springboot配置文件: application.yml application.properties(自带) yml的格式写起来稍微舒服一点 在application.properties ...
- 将springboot配置文件中的值注入到静态变量
SpringBoot配置文件分为.properties和.yml两种格式,根据启动环境的不同获取不同环境的的值. spring中不支持直接注入静态变量值,利用spring的set注入方法注入静态变量 ...
- SpringBoot配置文件 application.properties详解
SpringBoot配置文件 application.properties详解 本文转载:https://www.cnblogs.com/louby/p/8565027.html 阅读过程中若发现 ...
- Spring-Boot配置文件数据源配置项
Spring-Boot配置文件数据源配置项(常用配置项为红色) 参数 介绍 spring.datasource.continue-on-error = false 初始化数据库时发生错误时,请勿停止 ...
- 【日常错误】spring-boot配置文件读取不到
最近在用spring-boot做项目时,遇到自定义的配置文件无法读取到的问题,通过在appcation.java类上定义@PropertySource(value = {"classpath ...
- SpringBoot——配置文件加载位置及外部配置加载顺序
声明 本文部分转自:SpringBoot配置文件加载位置与优先级 正文 1. 项目内部配置文件 spring boot 启动会扫描以下位置的application.properties或者applic ...
- 【SpringBoot】SpringBoot配置文件及YAML简介(三)
SpringBoot配置文件 SpringBoot使用一个全局的配置文件,配置文件名是固定的; application.properties application.yml 配置文件的作用:修改Spr ...
随机推荐
- 算法-数位dp
算法-数位dp 前置知识: \(\texttt{dp}\) \(\texttt{Dfs}\) 参考文献 https://www.cnblogs.com/y2823774827y/p/10301145. ...
- TimSort源码详解
Python的排序算法由Peter Tim提出,因此称为TimSort.它最先被使用于Python语言,后被多种语言作为默认的排序算法.TimSort实际上可以看作是mergeSort+binaryS ...
- 安卓qq视频动态名片制作器
本软件来自互联网,仅供个人参考,严禁商业用途! 非常炫酷的diy动态名片教程,B格绝对高,内含软件教程代码,包会!
- latex参考文献删除[.s.l],[.s.n]
用latex写毕业论文的插入会议参考论文的时候可能会遇到编译后的文档里面一堆[.s.l],[.s.n]的问题. 这是因为ref里面会议条目找不到地址信息,所以用[.s.l],[.s.n]替代,只需要更 ...
- HBase数据导入导出工具
hbase中自带一些数据导入.导出工具 1. ImportTsv直接导入 1.1 hbase中建表 create 'testtable4','cf1','cf2' 1.2 准备数据文件data.txt ...
- Flink统计日活
.keyBy(0) .window(TumblingProcessingTimeWindows.of(Time.days(1), Time.hours(-8))) .trigger(Continuou ...
- 多任务-python实现-生成器相关(2.1.13)
@ 目录 1.概念 2.创建方法 3.通过send方式来启动 1.概念 通过列表生成式,我们可以直接创建一个列表,但是,受到内存限制,列表容量肯定是有限的,而且创建一个包含100万个元素的列表,不仅占 ...
- 免杀shellcode并绕过杀毒添加自启动
https://www.wtfsec.org/posts/%E5%85%8D%E6%9D%80shellcode%E5%B9%B6%E7%BB%95%E8%BF%87%E6%9D%80%E6%AF%9 ...
- angular 8 表单带文件上传接口
<div id="homework"> <form (ngSubmit)="doSubmit()" enctype="multipa ...
- 装逼篇 | 抖音超火的九宫格视频是如何生成的,Python 告诉你答案
1. 场景 如果你经常刷抖音和微信朋友圈,一定发现了最近九宫格短视频很火! 从朋友圈九宫格图片,到九宫格视频,相比传统的图片视频,前者似乎更有个性和逼格 除了传统的剪辑软件可以实现,是否有其他更加快捷 ...