三、配置文件
1.配置文件
Spring Boot使用一个全局的配置文件,配置文件名是固定的.
application.properties
配置文件的作用:修改SpringBoot自动配置的默认值:
2.YAML
1.基本语法
k:(空格)v: 表示一对键值对(空格必须有)
以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级的
service:
port: 8081
path: /hello
属性和值也是区分大小写敏感.默认可以不写引号。"" 可以将其中的转义符进行转义 , “张\n三”—>张回车三单引号和不加不会转义原样输出 。
2.值的写法
3.字面量:普通的值(数字、字符串、布尔):
k: v:字面直接来写:
字符串默认不用加上单引号或者双引号.
“”:双引号: 不会转义字符串里的特殊字符:特殊字符会作为本身想表达的意思
name: “zhangsan \n lisi” :输出 zhangsan 换行 lisi
‘’:单引号:会转义字符串里的特殊字符。特殊字符最终只是一个普通的字符串数据
name: “zhangsan \n lisi” :输出 zhangsan \n lisi
4.对象(属性和值)(键值对):
k: v: 在下一行来写对象的属性和值的关系;注意缩进
对象还是k: v:的方式
friends:
lastName: zhangsan
age: 20
行内写法:
friends: (lastName: zhangsan,age: 18)
5.数组(List、Set):
用-值表示数组中的一个元素
pets:
- cat
- pig
- dog
行内写法
pets: [cat,dog,pig]
3.配置文件值注入
1.@ConfigurationProperties 和@Value 的区别
@ ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个个指定 |
复杂类型封装 | 支持 | 不支持 |
松散绑定(松散语法) | 支持 | 不支持 |
SqEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
配置文件无论是properties | yaml 都可以获得到值.
如果说,我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,使用 @Value。
如果是,我们专门编写了一个JavaBean来和配置文件进行映射,我们就直接使 @ConfigurationProperties
JSR303数据校验在类上面加上 @Validated开启jsr303校验
2.配置文件yaml注入值数据校验
@Component
@ConfigurationProperties(prefix="person")
public class Person {
@Value("${person.last-name}")
private String lastName;
@Value("#{11*2}")
private int age;
@Value("false")
private Boolean boss;
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
//中括号可以省,大括号不能省
4.@PropertySource&@ImportResource
1.@PropertySource
@PropertySource加载指定的配置文件(只能加载properties,不能加载yaml)
创建一个person.propertie 再将 @PropertySource与这个配置文件绑定
@PropertySource(value="classpath:person.properties")
@Component
@ConfigurationProperties(prefix="person")
public class Person {
@Value("${person.last-name}")
private String lastName;
@Value("#{11*2}")
private int age;
@Value("false")
private Boolean boss;
private Date birth;
2.@ImportResource
导入Spring的配置文件,让配置文件里面的内容生效
Spring Boot里面没有Spring的配置文件, 我们自己编写的配置文件不能自动识别
想让Spring的配置文件生效,加载进来,@ImportResource标注在主配置类上
@ImportResource(locations = "classpath:beans.xml")
@SpringBootApplication
public class Srpingboot02Application {
public static void main(String[] args) {
SpringApplication.run(Srpingboot02Application.class, args);
}
导入spring的配置文件让其生效
不推荐编写Spring的配置文件
<?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="helloImport" class="com.xiaoming.srpingboot.controller.HelloImport">
</bean>
</beans>
Spring Boot推荐给容器中添加组件的方法:推荐使用全注解模式
1.配置===Spring配置文件+@configuration
2.使用 @Bean给容器中添加组件
@Configuration public class MyAppConfig { //将方法的返回值添加到容器中,容器中这个组件默认的id值就是方法名 @Bean public HelloImport helloImport(){//<bean id="helloImport">与上面的<bean>属性对应 return new HelloImport();//return <bean class="HelloImport"> } }
3.给配置文件注入属性值
类似用beans.xml配置bean(helloImport这个属性中包含了studentDao属性)
<bean id="helloImport" class="com.xiaoming.srpingboot.controller.HelloImport">
<property name="studentDao" ref="studentDao"></property>
</bean>
<bean id="studentDao" class="com.xiaoming.srpingboot.controller.HelloImport">
</bean>
用全注解来替换以上功能:
@Configuration
public class MyAppConfig {
//将方法的返回值添加到容器中,容器中这个组件默认的id值就是方法名
@Bean
public HelloImport helloImport(){
StudentDao studentDao = new StudentDao();
HelloImport helloImport = new HelloImport();
helloImport.setStudentDao(studentDao);
return helloImport;
}
}
4.配置文件占位符
1.随机数
${random.value} ${random.int} ${random.long} ${random.int(10)} ${random.int[1024,65536]}
2.占位符获取之前配置的值,如果没有可以用: 指定默认值
person.last-name=张三${random.uuid}
person.age=${random.int}
person.birth=2017/02/01
person.boss=true
person.maps.k1=v1
person.maps.k2=v2
person.lists=a,b,c
person.dog.name=${person.hello:hello}_dog//用的是其他配置文件的属性例如 .yaml,可以互相引用
person.dog.age=2
//${person.hello:hello} 引用变量的值 如果没有则用:后面的值作为默认值
5.Profile
1.多Profile文件
我们在主配置文件编写的时候,文件名可以是 application-profile.properties/yml (profile:环境名)
默认使用application.properties的配置
创建application-profile.properties
在配置文件里配
spring.profiles.active=dev//dev就是环境名 profile
2.yaml支持多文档块方式
server:
port: 8081
spring:
profiles:
active: dev//本次使用的环境
//主环境
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: prod #指定属于哪个环境
3.动态激活指定profile
1.在配置文件中指定(运行参数) -spring.profiles.active=dev
在编辑配置Edit Configurations中配置Program arguments中
2.命令行:
java -jar –spring.profiles.active=dev
3.虚拟机参数:(VM)
-Dspring.profiles.active=dev
优先级:dos命令行>arguments>options>properties>yaml
6.配置文件加载位置
properties和yaml的配置,相互补充。
springboot默认读取application.properties/application.yml,这两个文件可以存在于以下4个位置:
-
file:项目根目录/config
-
file:项目根目录
-
classpath:项目根目录/config
-
classpath:项目根目录
-
classpath:构建路径 例如src/java、src/resources…项目自动生成的application.properties
-
file:普通文件
如果配置冲突,优先级从上到下,不冲突:互补使用
配置项目名 (properties文件中)
server.servlet.context-path=/boot
-
7.外部配置加载顺序
- 运行参数:–spring.config.location=绝对路径
外部和内部同时存在,发生冲突,外部>内部 外部覆盖内部
- 通过命令行(补救)大量配置
java -jar 项目名 --spring.config.location=绝对路径
-
项目运行参数:(补救) 某个别
在在编辑配置Edit Configurations中配置Program arguments中 --需要覆盖的配置 例如 --server.port=8081
多个地方配置,如果冲突:命令行>外部文件>内部文件
8.自动配置原理
1.自动配置原理:
-
Spring Boot启动的时候加载主配置类,开启了自动配置功能**@EnableAutoConfiguration**
-
@EnableAutoConfiguration作用
-
利用AutoConfigurationImportSelector给容器中导入组件
-
可以查看**selectImports()**方法
-
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,\ ... 在第二个spring-boot-autofiguration中的spring.factories中
每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中。用他们来做自动配置
-
-
-
每一个自动配置类进行配置功能
-
以HttpEncodingAutoConfiguration(Http编码自动配置)为解释自动配置原理:
-
@Configuration(proxyBeanMethods = false)//表示这是一个配置类,给容器中添加组件 @EnableConfigurationProperties(HttpProperties.class)//启动指定类的ConfigurationProperties功能,将配置文件中对应的值和HttpEncodingAutoConfiguration绑定起来,并把HttpProperties.Encoding properties 加入到ioc容器中 @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)//spring底层是@Conditional注解,根据不同的条件,如果满足指定的条件,整个配置类里面的配置就会生效 判断当前应用是否是web应用 @ConditionalOnClass(CharacterEncodingFilter.class)//判断当前项目有没有这个类CharacterEncodingFilter;springMVC中进乱码解决的过滤器 @ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)//判断配置文件是否存在莫格配置 spring.http.encoding.enabled;如果不存在判断也成立 public class HttpEncodingAutoConfiguration { //他已经和SpringBoot的配置文件映射了 private final HttpProperties.Encoding properties; //只有一个有参构造器时,参数的值就会从容器中拿 public HttpEncodingAutoConfiguration(HttpProperties properties) { this.properties = properties.getEncoding(); } @Bean //给容器添加一个组件,这个组件的某些值需要从properties中获取 @ConditionalOnMissingBean 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; }
根据当前不同的条件判断,决定这个配置类是否生效
一旦这个配置类生效,这个配置类会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的。
-
-
所有在配置文件中能配置的属性都是在xxx.properties类中封装着,配置文件能配置什么就可以参照某个功能对应的这个属性类
@ConfigurationProperties(prefix = "spring.http")//从配置文件中获取指定的值和bean的属性进行绑定 public class HttpProperties {
1.我是这样理解的springboot启动的时候通过@EnableConfiguration内的selectImport方法找到Spring.facotries文件中的所有配置类并加载
2.而我们在全局配置文件中的配置通过@ConfigurationProperties绑定到相对应的Properties结尾的配置类
3并通过@EnableConfigurationProperties注解将properties结尾的配置类注入到spring容器中
-
精髓
- Spring Boot启动会加载大量的自动配置类
- 我们看我们需要的功能有没有Spring Boot默认写好的自动配置类
- 我们再来看这个自动配置类配置了哪些组件;(只要我们要用的组件有,我们就不需要配置了。)
- 给容器中自动添加组件的时候会从properties类获取某些属性,我们就可以在配置文件中指定这些属性的值。
自动配置类从对应的properties文件中获取值,生成组件,注入容器
xxxxAutoConfigration:自动配置类;
给容器中添加组件
xxxxProperties:封装配置文件中相关属性
2.细节
1.@Conditinal派生注解
作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置类里面的所有内容才生效;
自动配置类必须在一定的条件下才能生效。
我们怎么知道那些自动配置类生效了?
我们可以通过启动在properties 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)