SpringBoot系列二自动配置原理
1. 配置文件
Srping Boot 使用一个全局的配置文件,配置文件名是固定的:
- application.properties
- application.yml
配置文件的作用:修改SpringBoot配置的默认值
YAML(YAML Ain’t Markup Language)标记语言
标记语言:YAML更适合做配置文件语言,因为他是以数据为中心,比xml等标记语言更简洁
2. YAML语法
1. 基本语法
- K:(空格)V,表示一对键值对(空格是必须的);
YAML中以空格缩进的方式来体现层级关系的;左对齐的数据可以认为是属于同一级的。 - 属性和值也是大小写敏感的
2. 值的写法
1、 字面量:普通的值(数字,字符串,布尔)
直接是K: V的形式,但是需要注意单双引号的区别
- ""双引号: 如果里面出现可以可转义的字符,如\n, 输出时就会变成换行
- ''单引号: 如果里面出现可以可转义的字符,如\n, 则不会做任何处理,直接输出\n
2、对象,Map(键值对)
也是K: V的形式,但是可以有两种表达方式,跨行和不跨行
- 键值对
friends:
lastName: lisi
age: 18
- 行内写法
friends: { lastName: lisi, age: 18}
3、数组(List,Set)
- 用 - 值 表示数组中的一个元素
pets:
- cat
- dog
- pig
- 行内写法
pets: [cat,dog,pig]
3. 配置文件值注入
配置文件
person:
lastName: lisi
age: 18
isGirl: false
#注意时间格式需要注意,如果是2020-11-14格式,需要在bean中进行特殊处理
birthDay: 2020/11/14 12:24:00
maps: {k1: v1, k2: v2}
lists:
- dog
- cat
dog:
name: 小狗
age: 2
javaBean
/**
* 将配置文件中配置的每个属性值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定,
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,容器才能提供@ConfigurationProperties功能
* @ConfigurationProperties(prefix = "person") 默认从全局文件中获取值
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
private String lastName;
private Integer age;
private Boolean isGirl;
private Date birthDay;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
// toString ...
// getter setter ....
}
可以导入配置文件处理器,以后编写配置就有提示了
<!-- 导入配置文件处理器,配置文件进行绑定就会有提示 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
application.properties中配置
#配置person的值
person.last-name=张三
person.age=12
person.isGirl=false
person.birthDay=2020/11/14
person.maps.k1=v1
person.maps.k3=v3
person.lists=a,b,c
person.dog.name=dog
person.dog.age=15
但是配置时,需要注意,编码,properties的默认文件类型可能是GBK或者UTF-8,所以需要修改编码

3. 配置文件相关注解
1. @ConfigurationProperties和@Value
区别 | @ConfigurationProperties | @Value |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
松散绑定(松散语法) | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂数据类型封装 | 支持 | 不支持 |
解释:
- 松散语法,就是last-name可以解析成lastName,前者支持,后者不支持
- SpEL: #{10*2},前者不支持,后者支持
- JSR303数据校验:就是通过类添加@Validated,然后属性可以使用类似@Email的注解,实现对这个属性的值格式的限制,前者支持,后者不支持
- 复杂数据类型封装:就是对Map,List等类型注入时,前者支持,后者不支持
2. @PropertySource 和 @ImportResource
1. @PropertySource
作用:@PropertySource 用于加载指定的配置文件
用法:@PropertySource(value = {“classpath:person.properties”})
注意:
- @Component
@ConfigurationProperties(prefix = “person”)
这两个注解不能去掉,要不然找不到文件,注入值为null - value = {“classpath:person.properties”} 中的classpath不能去掉,要不然默认从根目录下找,依旧找不到,值为null
2. @ImportResource
作用:导入Spring的配置文件,让配置文件里面的内容生效
用法:在SpringBoot的主配置类上 @ImportResource(locations = “classpath:bean.xml”)
注意:Spring Boot里面灭有Spring配置文件,自己编写的配置文件也不能自动识别想让Spring的配置文件,使用 @ImportResource标注在主配置类上,使配置文件生效。但是这种方式比较麻烦
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="helloService" class="com.wz.service.HelloService"></bean>
</beans>
其他方式:
- 使用 @Configuration的方式
/**
* @Configuration 指明当前类是一个配置类,就是来替代之前的Spring配置文件
*/
@Configuration
public class ApplicationConfig {
//将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名。
@Bean
public HelloService helloService(){
return new HelloService();
}
}
- 另一种就是使用注解的方式:
@Service
public class HelloService {
}
4. 配置文件占位符
1. 随机数
${random.uuid}、${random.int}、${random.long}
${random.int(10)}、${random.int[1024,65536]}、${random.value}
2. 占位符获取之前配置的值
person.last-name=张三${random.uuid}
person.age=${random.int}
person.birthDay=2020/11/14
person.maps.k1=v1
person.maps.k3=v3
person.lists=a,b,c
person.dog.age=15
person.girl=true
#person.dog.name=${person.last-name}_dog
#如果person.name没有值,将直接输出${person.name},也可以使用:name来指定默认值
person.dog.name=${person.name:name}_dog
5. Profile
1. 多profile文件
可以配置多个properties文件,分别指定开发和生产环境的配置文件application-{profile}.properties
如: application-dev.properties,application-prod.properties
默认使用的application.properties文件。
2. yml支持多文档块方式
“—”:表示可以将一个yml文件分成多个文档块,每个文档块互不影响
server:
port: 9090
spring:
profiles:
active: dev
---
server:
port: 9091
#指定文档块属于开发环境
spring:
profiles: dev
---
server:
port: 9092
#指定文档块属于生产环境
spring:
profiles: prod
3. 激活指定profile
- 在配置文件中指定 spring.profiles.active=profile 如:spring.profiles.active=dev
- 命令行激活
- 使用java -jar jar包名 --spring.profiles.active=dev
- 启动时配置普通参数 --spring.profiles.active=dev
- 启动时配置VM参数 -Dspring.profiles.active=dev,优先级低于普通参数
6. 配置文件加载位置
1. 优先级
springboot 会自动扫描以下位置的application.properties或者yml文件作为SpringBoot的配置文件
- ./config/: 项目根目录下/config文件夹下
- ./:项目根目录下
- classpath/config/: classpath下的config文件下,即resources文件夹的config
- classpath/: classpath下的文件,即resources文件夹下
2. spring.config.location
可以通过 spring.config.location来改变默认配置文件的位置
步骤:项目打包好后,使用命令行参数的形式,在启动时指定配置文件的新位置,外部配置文件优先级最高,两个配置文件将形成互补配置
注意:server.servlet.context-path=/config02 用于指定项目访问路径,SpringBoot2.0版本之后弃用了之前的server.context-path
7. 外部配置加载顺序
配置顺序
SpringBoot也可以从以下位置加载配置,优先级从上到下,高优先级配置覆盖低优先级配置,并且所有的配置形成互补配置
1.命令行参数
即在命令行用带参数的方式启动
如:java -jar jar包名 --server.port=8088 --server.servlet.context-path=/config02
2.来自java:comp/env的JNDI属性
3.Java系统属性( System.getProperties() )
4.操作系统环境变量
5.RandomvaluePropertySource配置的random.*属性值
jar包外部的配置文件优先级高于内部的配置文件
带profile
6.Jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
7.jar包内部的application-{profile}.properties或application.yml(带spring.profile)配置文件
不带profile
8.jar包外部的application.properties或application.yml(不带spring.profile)配置文件
9.jar包内部的application.properties或application.yml(不带spring.profile)配置文件
10.@Configuration注解类上的@PropertySource
11.通过SpringApplication.setDefaultProperties指定的默认属性
8. 自动配置原理
1. 自动配置原理
- Spring Boot 启动时,开启了自动配置功能 @EnableAutoConfiguration
- @EnableAutoConfiguration 作用 :
- 使用@Import({AutoConfigurationImportSelector.class})给容器中导入AutoConfigurationImportSelector
- 查看 selectImports() 方法
- List
configurations = this.getCandidateConfigurations(annotationMetadata, attributes);
获取候选配置
//4. 开启自动配置类,并传入来类名
SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
//3. 返回类名
protected Class<?> getSpringFactoriesLoaderFactoryClass() {
return EnableAutoConfiguration.class;
}
//2. loadFactoryNames 返回加载到properties,返回list
return (List)loadSpringFactories(classLoaderToUse).getOrDefault(factoryTypeName, Collections.emptyList());
//1. loadSpringFactories 扫描所有的jar包,加载类路径下的 META-INF/spring.factories文件,
Enumeration urls = classLoader.getResources("META-INF/spring.factories");
- 最终将META-INF/spring.factories 中 EnableAutoConfiguration 的值加载到容器中,每一个这样的XXXAutoConfiguration类都是容器中的一个组件,都加载到容器中,用他们来做自动配置,具体如下:
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.Neo4jReactiveDataAutoConfiguration,\
org.springframework.boot.autoconfigure.data.neo4j.Neo4jReactiveRepositoriesAutoConfiguration,\
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.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.neo4j.Neo4jAutoConfiguration,\
org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\
org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\
org.springframework.boot.autoconfigure.r2dbc.R2dbcTransactionManagerAutoConfiguration,\
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 为例,解释自动配置原理
//表示这是一个配置类
@Configuration(proxyBeanMethods = false)
//启动指定的类ConfigurationProperties功能,将配置文件中对应的值和ServerProperties绑定起来,并将ServerProperties加入到容器中
@EnableConfigurationProperties({ServerProperties.class})
//Spring底层@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效
//ConditionalOnWebApplication,判断当前应用是否是web应用,如果是,注解生效
@ConditionalOnWebApplication(type = Type.SERVLET)
//判断当前项目有没有这个类,CharacterEncodingFilter,SpringMvc中进行乱码解决的过滤器
@ConditionalOnClass({CharacterEncodingFilter.class})
//判断配置文件中是否存在server.servlet.encoding.enabled配置,
//即配置文件中不配置server.servlet.encoding.enabled=true,也是默认生效的
@ConditionalOnProperty(prefix = "server.servlet.encoding",value = {"enabled"}, matchIfMissing = true)
public class HttpEncodingAutoConfiguration {
//已经和SpringBoot的配置文件映射了
private final Encoding 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(org.springframework.boot.web.servlet.server.Encoding.Type.REQUEST));
filter.setForceResponseEncoding(this.properties.shouldForce(org.springframework.boot.web.servlet.server.Encoding.Type.RESPONSE));
return filter;
}
}
根据当前不同的条件判断,决定这个配置类是否生效
- 所有的配置文件中能配置的属性,都在xxxProperties中,配置文件能配置什么参照这个类就行
//从配置文件中获取指定的值和bean的属性进行绑定
@ConfigurationProperties(prefix = "server", gnoreUnknownFields = true)
public class ServerProperties {}
2. 总结
- @EnableConfigurationProperties将xxxProperties类,添加到spring容器中;
- 然后在通过@ConfigurationProperties将全局配置文件中配置的属性绑定到对应的xxxProperties类中;
- 最后对应类的构造方法注入的方式将xxxProperties类注入对应的对象中,从而获取到全局配置中配置的属性。
3. 注意细节
@Conditional派生注解
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置文件中配置的内容才生效
自动配置类需要在一定的条件下才能生效
通过在全局配置文件中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)
//自动配置类吗没有启动的
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)