一、Spring Boot全局配置文件:1)、application.properties名称固定。2)、application.yml 配置文件。两个文件的作用:可以覆盖SpringBoot配置的默认值。
◀ YAML(is not a Markup Language:不仅仅是一个标记语言):以前的配置文件,大多是xx.xml文件,而YAML是以数据为中心,比json、xml等更适合做配置文件。
#普通配置文件.properties的语法
#server.port=80
#XML的写法
#<server>
# <port>8080<port/>
#<server/>
#yml 以数据为中心的语法
server:
port: 8080
◀ YML语法:基本语法:k:(空格)v--->表示一对键值对。(以空格缩进来控制层级关系;只要是左对齐的一列数据,都是同一层级)属性和值也是大小写敏感。
server:
port: 8080
path: /hello
spring:
profiles: dev
◀ 值得写法:1)字面量:普通的值(数字、字符串、布尔),字符串默认是不用加上单引号或者双引号,但也可以加,但是有区别:双引号,不会转义字符串里面的特殊字符,特殊字符会作为本身想表达的意思。单引号,会转义特殊字符,特殊字符最终只是一个普通的字符串数据。
2)、对象(属性和值)或者Map(键值对)的表达—>k: v形式,对象还是k: v的方式。比较抽象,我们举个栗子看看:
#yml正常写法
friends:
lastName: zhangsan
age: 20
#行内写法
friends: {lastName: zhangsan,age: 20}
3)、数组(List、Set)用 ‘- 值’ 表示数组中的一个元素,也举一个栗子:
# yml正常写法 -值 形式
pets:
- cat
- dog
#行内写法
pets: [cat,dog]
◀ 配置文件注入:测试上面数据赋值是否正确。
1)、准备配置文件:application.yml
person:
lastName: zhangsan
age: 20
boss: false
birth: 2018/8/20
map: {k1: v1,k2: v2}
lists: [listi,zhaoliu]
dog:
name: gou
age: 2
2)、准备JavaBean:@ConfigurationProperties(prefix ="person")表示将配置文件中的person的每一个属性映射到这个组件中,但只有这个组件是容器中的组件,才能提供功能。需要使用@Component标注才能成为容器组件。
@Component
@ConfigurationProperties(prefix ="person")
public class Person {
private String lastName;
private Integer age;
private boolean boss;
private Date birth;
private Map<String,String> map;
private List lists;
private Dog dog;
}
3)、优化:当准备2中的文件,会提示我们“Spring Boot Configuration Annotation ...”点击去后会发现如下starters信息,那么我们将此配置于pom文件中,作用:当我们在配置文件中,给带有@ConfigurationProperties的实体类赋值时会有属性提示。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
4)、测试: 进入test目录底下的类目录,直接导入person输入,查看是否已赋值即可。
//使用Spring的驱动器,不用再使用JUnit的驱动器了
@RunWith(SpringRunner.class)
@SpringBootTest
public class HellowordQuickStartApplicationTests {
//在测试期间可以类似编码一样进行自动注入
@Autowired
Person person;
@Test
public void testPersion(){
System.out.println(person);
}
}
5)、properties中的语句与yml不同,以下是properties的配置语句。
#person.lastName=张三 也是可以的
person.last-name=张三
person.age=18
person.birth=2013/04/23
person.boss=false
person.map.key1=v1
person.map.key2=v2
person.lists=a,b,c
person.dog.name=dog
person.dog.age=2
6)、测试的时候可能会出现乱码,设置如下。properties默认的编码时ASK码,我们需要将其设置为UTF-8来解决乱码问题。
7)、第二种赋值方式:@ Value(“字面量/${key}从环境变量、配置文件中获取值/#{SpEL}”)---三种传值方式
@Component
//@ConfigurationProperties(prefix ="person")
public class Person {
//@email @Value不支持校验(JSR303数据校验)
@Value("${person.last-name}")
private String lastName;
//SPEL
@Value("#{22*3}")
private Integer age;
@Value("true")
private boolean boss;
● @Vaule与@ConfigurationProperties两者的区别如下:(其实@Value最多用在获取单个值的时候使用)
@configuration | @value | |
功能 | 批量注入配置文件中的属性 | 每个属性单独配置 |
松散绑定(松散语法) | 支持(大小写不敏感) | 不支持(与配置文件保持一致) |
SpEL | 不支持(不能用于逻辑计算) | 支持#{逻辑计算} |
JSR303数据校验 | 支持@validated | 不支持 |
复杂类型封装 | 支持 | 不支持(map对象) |
二、@PropertySource与@ConfigurationProperties之间的区别:@ConfigurationProperties:默认从全局配置文件中加载值。
● @PropertySource:指向自己定义的properties配置文件,新建person.properties配置文件(省略),如下获取值。
//优先级高于@ConfigurationProperties(prefix ="person")
@PropertySource(value = {"classpath:person.properties"})
@Component
//@ConfigurationProperties(prefix ="person")
//@Validated
public class Person {
● @ImportResource:导入Spring的配置文件,让配置文件里面的内容生效 。
1)、定义配置文件bean.xml(以前的配置,SpringBoot不这么用)
<?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.atguigu.Servers.HelloService"></bean>
</beans>
2)、在主程序中使用@ImportResource注解导入bean.xml配置文件
@ImportResource(locations={"classpath:bean.xml"})
@SpringBootApplication
public class HellowordQuickStartApplication {
● SpringBoot中(配置类====配置文件xml)推荐使用配置类,如下创建:
//@Configuration指明当前类是一个配置类 替代配置文件
@Configuration
public class MyAppConfig {
//@bean注解就相当于<bean></bean>标签
@Bean
//方法名就相当于xml中的id , 项目启动时就会将组件加入容器中
public HelloService helloService(){
System.out.println("@Bean给容器中添加组件");
return new HelloService();
}
}
三、配置文件占位符
1)、随机数(了解即期)
${random.value}、${random.int}、${random.log}、${random.int(10)}
2)、占位符(当属性不存在时,可以给一个默认值,例如下面age属性值得获取)
persion.last-name=张三
persion.dog.name=${persion.last_name}_dog
perdion.dog.age=${persion.noexistage:20}
四、Profile:是Spring对不同环境提供不同配置功能的支持,可以通过激活、指定参数等方式快速切换环境:
1)、多profile文件形式(了解一下,我们使用更多的是2中的yml形式):
我们可以编写多个配置文件,对应多个场景(开发、测试、生产等),文件名可以是application-{profile}.properties/yml的形式命名,例如:application-dev.properties
项目启动时默认使用application.properties的配置,如果要激活开发配置文件,在application.properties中输入如下激活信息。
#激活dev开发模式的配置文件,就不用application.properties文件的配置了
spring.profiles.active=dev
2)、yml支持多文档块方式(推荐使用):通过“---”来划分文档块,Document表示所处模块的位置/总块 。
# --- 称为多文档快 , 简写1中的形式
---
server:
port: 8080
path: /hello
# 如下为激活profiles ,如果不激活则默认为Document1中的配置
spring:
profiles:
active: dev
---
server:
port: 8084
spring:
profiles: prod
---
server:
port: 8081
spring:
profiles:
active: dev
3)、激活指定profile方式,上面用的都是第一种:
(1)、在默认配置application.properties中设置spring.profiles.active属性
spring.profiles.active=dev
(2)、命令行:--spring.profiles.active=dev
命令行运行jar包的方式:java -jar xxx.jar --spring.profiles.active=dev;
(3)、虚拟机参数:-Dspring.profiles.active=prod;
五、配置文件加载位置:也就优先级
SpringBoot启动会扫描一下位置的application.properties或者application.yml文件作为SpringBoot的默认配置文件
(1)、file:./config/ (项目底下的config目录)
(2)、file:./ (直接位于项目底下的配置文件)
(3)、classpath:/config/ (config文件默认没生成,需要自己创建)
(4)、classpath:/ (项目创建后,配置文件默认位置)
以上是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置的相同内容。
我们也可以通过spring.config.location来改变默认配置(项目打包成功以后,我们可以使用命令行参数的形式,启动项目来指定配置文件的新位置;指定的配置文件会共同起作用,形成互补作用),这个优先级肯定最高了。而且我们要知道,打jar包的时候只包含src底下的main和resource文件,1、2中的不会被打包进去。其实将jar包与配置文件*.yml等放在同一个目录下的情况也比较多常见,因为灵活。项目启动时可以自动加载同目录下的*.yml等配置文件。且优先级高于内部的配置文件,之间互补配置。
#命令行添加配置,优先级最高
java -jar xxx.jar --spring.config.location=d:\xxx.properties
六、自动配置原理:
【1】、SpringBoot启动的时候加载主配置类,@SpringBootApplication下开启了主配置功能@EnableAutoConfiguration
【2】、@EnableAutoConfiguration作用:1)、利用EnableAutoConfigurationImportSelector给容器导入一些组件。
2)、可以查看selectImports()方法的内容:
List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置。
SpringFactoriesLoader.loadFactoryNames()扫描所有jar包类路径下 META‐INF/spring.factories把扫描到的这些文件的内容包装成properties对象从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
【3】、将 类路径下 META-INF/spring.factories 里面配置的所有EnableAutoConfiguration的值加入到了容器中;
# EnableAutoConfiguration 对应 @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.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.CassandraReactiveDataAutoConfiguration,\
每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中;用他们来做自动配置;
【4】、每一个自动配置类进行自动配置功能,以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理;
@Configuration //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties(HttpEncodingProperties.class) //启动指定类的
ConfigurationProperties功能;将配置文件中对应的值和HttpEncodingProperties绑定起来;并把
HttpEncodingProperties加入到ioc容器中
@ConditionalOnWebApplication //Spring底层@Conditional注解(Spring注解版),根据不同的条件,如果
//满足指定的条件,整个配置类里面的配置就会生效; 判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass(CharacterEncodingFilter.class) //判断当前项目有没有这个类
CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器;
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing =
true) //判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=true,也是默认生效的;
public class HttpEncodingAutoConfiguration {
//他已经和SpringBoot的配置文件映射了
private final HttpEncodingProperties properties;
//只有一个有参构造器的情况下,参数的值就会从容器中拿
public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
this.properties = properties;
}
@Bean //给容器中添加一个组件,这个组件的某些值需要从properties中获取
@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;
}
根据当前不同的条件判断,决定这个配置类是否生效?一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
【5】、所有在配置文件中能配置的属性都是在xxxxProperties类中封装者;配置文件能配置什么就可以参照某个功能对应的这个属性类
@ConfigurationProperties(prefix = "spring.http.encoding") //从配置文件中获取指定的值和bean的属
性进行绑定
public class HttpEncodingProperties {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF‐8");
精髓:1)、SpringBoot启动会加载大量的自动配置类
2)、我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;
3)、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
4)、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;
xxxxAutoConfigurartion:自动配置类,给容器中添加组件。
xxxxProperties:封装配置文件中相关属性;
七、@ConditionalOnxxx中的@Conditional派生注解(Spring注解版原生的@Conditional作用)作用:必须是@Conditional指定的条件成立,才给容器中添加组件,配置配里面的所有内容才生效。
● 自动配置类必须在一定的条件下才能生效,那么我们如何知道哪些配置类生效哪些没有生效,其实我们可以通过在配置文件启用 debug=true属性,就可以查看哪些配置类生效。
debug=true
▶ 通过控制台打印自动配置报告,我们就可以知道哪些自动配置类生效(Positive matches:匹配成功的自动配置类)
Positive matches:
-----------------
CodecsAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.http.codec.CodecConfigurer'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
CodecsAutoConfiguration.JacksonCodecConfiguration matched:
- @ConditionalOnClass found required class 'com.fasterxml.jackson.databind.ObjectMapper'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
CodecsAutoConfiguration.JacksonCodecConfiguration#jacksonCodecCustomizer matched:
- @ConditionalOnBean (types: com.fasterxml.jackson.databind.ObjectMapper; SearchStrategy: all) found bean 'jacksonObjectMapper' (OnBeanCondition)
DispatcherServletAutoConfiguration matched:
- @ConditionalOnClass found required class 'org.springframework.web.servlet.DispatcherServlet'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
- found ConfigurableWebEnvironment (OnWebApplicationCondition)
▶ 自动配置未生效类(Negative matches:匹配失败的自动配置类)
Negative matches:
-----------------
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.ActiveMQConnectionFactory' (OnClassCondition)
AopAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'org.aspectj.lang.annotation.Aspect', 'org.aspectj.lang.reflect.Advice', 'org.aspectj.weaver.AnnotatedElement' (OnClassCondition)
ArtemisAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required classes 'javax.jms.ConnectionFactory', 'org.apache.activemq.artemis.jms.client.ActiveMQConnectionFactory' (OnClassCondition)