二、SpringBoot配置文件
1、配置文件
Spring Boot使用全局的配置文件,文件名是固定的。
- application.properties
- application.yml
配置文件的作用:修改Spring Boot自动配置的默认值。
2、YAML语法
server:
port: 8081
path: /hello
person:
name: zhangsan
age: 20
boss: false
birth: 2017/11/12
#map写法1:行内
maps1: {k1: v1, k2: v2}
#map写法2
maps2:
k3: v3
k4: v4
#数组写法1
lists1:
- l1
- l2
#数组写法2:行内
lists2: [l3, l4]
# 对象
dog:
name: 小狗
age: 2
3、配置文件值注入
3.1、编写javaBean
/**
* 将配置文件中的配置的每一个属性值,映射到组件中
* @ConfigurationProperties: 告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定。
* prefix: 配置文件中的prefix指定的属性下的所有属性与该组件属性一一对应。
*
* @ConfigurationProperties: 默认从全局配置文件中获取值
*
* 只有这个组件是容器中的组件,容器才能提供@ConfigurationProperties功能。
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person implements Serializable {
private String name;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
//省略getter和setter
}
可以导入配置文件处理器,然后配置属性的时候就会有提示
<!--配置文件处理器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
3.2 @ConfigurationProperties
-
告诉SpringBoot将本类中的属性和配置文件中相关的配置进行绑定。
-
prefix: 配置文件中的prefix指定的属性下的所有属性与该组件属性一一对应。
-
默认从全局配置文件中获取值
3.3、修改idea的properties默认文件编码格式
SpringBoot中properties配置文件编码改成UTF-8.png3.4、@Value和@ConfigurationProperties获取值的区别
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个一个指定 |
松散绑定 | 支持松散绑定 | 不支持松散绑定 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持,@Validated @Email等 | 不支持 |
复杂类型封装 | 支持 | 不支持 |
总结:
- 如果只是需要配置文件中的某个属性,建议使用 @Value。
- 如果需要映射到某个配置类中的属性,建议使用 @ConfigurationProperties。
3.5、配置文件注入值数据校验:
@Component
@ConfigurationProperties(prefix = "person")
@Validated
public class Person implements Serializable {
@Email
private String name;
private Integer age;
private Boolean boss;
private Date birth;
private Map<String, Object> maps;
private List<Object> lists;
private Dog dog;
//省略getter和setter
}
3.6、@PropertySource
-
用于读取application.properties之外的properties文件
-
该注解需要配合@ConfigurationProperties一起使用
-
需要在@ConfigurationProperties中指定使用的前缀prefix(如果有)
-
需要在@PropertySource指定加载的properties文件
#employee.properties
employee.name=lisi
employee.age=30
employee.birth=2017/11/11
employee.boss=false
@Component
@PropertySource(value = {"classpath:employee.properties"},encoding = "UTF-8")
@ConfigurationProperties(prefix = "employee")
public class Employee implements Serializable {
private String name;
private Integer age;
private Date birth;
private Boolean boss;
//省略getter和setter
}
3.7、@ImportResource
- 导入spring的配置文件,让配置文件里面的内容生效。
SpringBoot里面没有Spring的配置文件,即使用Spring项目中的xml格式的配置文件,SpringBoot不能自动识别,如果想让Spring的配置文件生效,需要使用@ImportResource标注在一个配置类上,推荐标注在主配置类上。
<!-- beans.xml -->
<?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="org.com.cay.spring.boot.service.HelloService"></bean>
</beans>
@ImportResource(locations = {"classpath:beans.xml"})
SpringBoot推荐给容器中添加组件的方式:使用注解 @Bean
/**
* @Configuration: 指明当前类是一个注解类,用来代替原来的Spring的xml配置文件
*/
@Configuration
public class MyConfig {
//将方法的返回值添加到容器中,容器中这个组件默认的id为方法名
@Bean
public HelloService helloService(){
System.out.println("添加组件:helloService");
return new HelloService();
}
}
4、配置文件占位符
4.1、随机数
-
${random.int}
-
${random.long}
-
${random.uuid}
-
${random.int(value, [max])}
-
...
4.2、占位符
-
可以引用之前的属性值,如果没有可以使用默认值:
-
例如:{aaa}不存在,则使用default代替aaa的值。
-
number=${random.int}
name=${random.uuid}
abc=${random.int(100,1000)}
content=${name}得到的值是${number}
#xyz=${random.int}
#如果${xyz}不存在,则使用0000代替
text=${abc}-${xyz:0000}
5、Profile
Profile是Spring对不同环境提供不同配置功能的支持,可通过激活、指定参数等方式快速切换环境。
5.1、多Profile文件
在主配置文件编写的时候,文件名可以是application-{profile}.properties/yml
- application.properties: 默认全局配置文件
- application-dev.properties/yml: 开发环境
- application-prod.properties/yml: 生产环境
- application-test.properties/yml: 测试环境
5.2、yml支持多文档块方式
server:
port: 8080
spring:
profiles:
active: dev
---
server:
port: 8084
spring:
profiles: dev
---
server:
port: 8085
spring:
profiles: prod
---
server:
port: 8086
spring:
profiles: test
5.3、激活指定Profile
- 在全局配置文件中指定
spring.profiles.active=...
来指定当前的环境,并使用对应的application-{profile}.properties/yml作为当前环境使用的配置信息。 - 虚拟机参数:
Edit Configurations
--->VM options
---->-Dspring.profiles.active=...
- 命令行:
- 打包用命令
java -jar xxxx.jar --spring.profiles.active=...
- IDEA运行设置:
Edit Configurations
--->Program arguments
---->--spring.profiles.active=xx
- 打包用命令
6、配置文件加载位置
Spring Boot启动会扫描以下位置的application.properties/yml文件作为Spring Boot默认配置文件:
Spring Boot官方文档章节:加载application.properties配置文件
- 外置,在相对于应用程序运行目录的/config子目录里
- 外置,在应用程序运行的目录里
- 内置,在resources/config包内
-
内置,在classpath根目录(resouces目录下)
application.properties优先级.png
总结:
- 优先级由高到低,对于相同的属性配置,高优先级的配置会覆盖优先级低的配置;对于其他不同的属性配置,则会进行互补。
- 优先级相同的情况下,同时有application.properties和application.yml,那么application.yml里面的属性就会覆盖application.properties里的属性。
可以通过spring.config.location来改变默认的配置文件位置:
项目打包好以后,使用命令行参数的形式
--spring.config.location=...
来启动项目,用来指定配置文件的新位置,从而使指定的新配置文件和包内的默认加载的配置文件共同起作用行程互补配置。
java -jar spring-boot-02-config-SNAPSHOT.jar --spring.config.location=F:/application.properties
7、外部配置加载顺序
Spring Boot也可以从以下位置加载配置; 优先级从高到低;高优先级的配置覆盖低优先级的配置,所有的配置会形成互补配置
- 命令行参数
所有的配置都可以在命令行上进行指定
java -jar spring-boot-02-config-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
多个配置用空格分开; --配置项=值
当然由于使用命令行参数或修改默认的属性配置的方式并一定是安全的,所以可以通过代码禁止使用命令行。
SpringApplication application = new SpringApplication(SpringBoot02ConfigApplication.class);
//禁止通过命令行参数修改默认配置属性
application.setAddCommandLineProperties(false);
//启动
application.run(args);
- 来自java:comp/env的JNDI属性
- Java系统属性(System.getProperties())
- 操作系统环境变量
- RandomValuePropertySource配置的random.*属性值
由jar包外 ----向----> jar包内进行寻找;
优先加载带profile
- jar包外部的application-{profile}.properties或application.yml(带spring.profile)配置文件
- jar包内部的application-{profile}.properties或application.yml(带spring.profiles)配置文件
再来加载不带profile
- jar包外部的application.properties或application.yml(不带spring.profile)配置文件
- jar包内部的application.properties或application.yml(不带spring.profile)配置文件
-
@Configuration注解类上的@PropertySource
-
通过SpringApplication.setDefaultProperties指定的默认属性
//使用指定的配置文件 SpringApplication application = new SpringApplication(SpringBoot02ConfigApplication.class); //加载指定的配置文件 InputStream is = SpringBoot02ConfigApplication.class.getClassLoader().getResourceAsStream("app.properties"); Properties properties = new Properties(); try { properties.load(is); } catch (IOException e) { e.printStackTrace(); } //设置属性 application.setDefaultProperties(properties); //启动 application.run(args);
所有支持的配置加载来源:参考官方文档
8、自动配置原理
配置文件能配置的属性请参照:官方所有自动配置属性
8.1、自动配置原理
-
Spring Boot启动的时候加载主配置类,开启了自动配置功能@EnableAutoConfiguration
-
@EnableAutoConfiguration作用:
- 利用EnableAutoConfigurationImportSelector给容器中导入一些组件:
- 可以查看selectImports()方法的内容:
List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
内部:
List<String> configurations = SpringFactoriesLoader.loadFactoryNames( getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
扫描所有jar包类路径下的
META-INF/spring.factories
,然后把扫描到这些文件的内容包装成Properties对象,从Properties中获取到 EnableAutoConfiguration.class 类对应的值,然后添加到容器中。# 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) @ConditionalOnWebApplication @ConditionalOnClass(CharacterEncodingFilter.class) @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true) public class HttpEncodingAutoConfiguration { //... @Bean @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; } }
-
@EnableConfigurationProperties: 启动指定类的ConfigurationProperties功能,将配置文件中的值和xxxxProperties绑定起来,并把属性value的值加入到Spring的IOC容器中。
- 所有在配置文件中能配置的属性都是在xxxProperties类中封装着,配置文件能配置哪些属性就可以参照某个功能对应的属性类
@ConfigurationProperties(prefix = "spring.http.encoding")//从配置文件中获取指定的值与bean的属性进行绑定 public class HttpEncodingProperties { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); }
@Conditional:Spring底层注解,可以根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效。
@ConditionalOnWebApplication:判断当前应用是否是web应用,如果是,则当前配置类就生效。
@ConditionalOnClass:判断当前项目中有没有value所指定的类
@ConditionalOnProperty:判断配置文件中是否存在某个配置项:spring.http.encoding.enabled, matchIfMissing表示如果不存在该配置下,则表示该配置项的值为matchIfMissing指定的值。
以
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
为例,判断是否配置了spring.http.encoding.enabled该项,如果未配置,则该值也默认为生效的。 -
@EnableConfigurationProperties: 启动指定类的ConfigurationProperties功能,将配置文件中的值和xxxxProperties绑定起来,并把属性value的值加入到Spring的IOC容器中。
总结:自动配置类是根据当前不同的条件判断,决定该配置类是否生效,一旦该配置类生效后,就会向容器中添加各种组件,这些组件的属性都是从对应的Properties类中获取,而这些类里面的每一个属性又是和配置文件绑定。
8.2、细节
@Conditional派生注解(Spring注解版原生的@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存在指定项 |
自动配置类必须在一定的条件下才能生效。
可以在application.properties中设置 debug=true 属性,这样项目启动过程中控制台会打印输出自动配置报告,这样就可以很方便的知道哪些自动配置类生效了。
=========================
AUTO-CONFIGURATION REPORT
=========================
Positive matches:(自动配置类启用的)
-----------------
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- @ConditionalOnWebApplication (required) found StandardServletEnvironment (OnWebApplicationCondition)
...
Negative matches: (没有启动,没有匹配成功的自动配置类)
-----------------
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
...