目录
1、@ConfigurationProperties & @Value
2、@PropertySource&@ImportResource&@Bean
2、@Conditional派生注解(Spring注解版原生的@Conditional作用)
SpringBoot使用一个全局的配置文件用于修改SpringBoot自动配置的默认值,并且配置文件名是固定的
- application.properties
- application.yml
1、YAML语法
1、基本语法
- 大小写敏感
- 使用缩进表示层级关系
- 缩进不允许使用tab,只允许空格
- 缩进的空格数不重要,只要相同层级的元素左对齐即可
- '#'表示注释
server:
port: 8080
servlet:
context-path: /demo
2、数据类型
- 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
- 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
- 纯量(scalars):单个的、不可再分的值
参考地址:YAML 入门教程
2、配置注入
1、@ConfigurationProperties&@Value
配置文件
person:
name: shinb
age: 20
boss: false
birth: 2021/10/10
maps: {k1: v1,k2: 12}
lists:
‐ lisi
‐ zhaoliu
dog:
name: 小狗
age: 8
java bean
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties 告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
* @ConfigurationProperties 覆盖@Value
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
*/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
@Value("${person.name}")
private String name;
@Value("#{12*2}")
private Integer age;
@Value("true")
private Date birth;
private Map<String,Object> maps;
private List<Object> lists;
private Dog dog;
//getters setters
}
public class Dog {
private String name;
private Integer age;
//getters setters
}
2、@PropertySource&@ImportResource&@Bean
@PropertySource:加载指定的配置文件
/**
* 将配置文件中配置的每一个属性的值,映射到这个组件中
* @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
* prefix = "person":配置文件中哪个下面的所有属性进行一一映射
*
* 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
* @ConfigurationProperties(prefix = "person")默认从全局配置文件中获取值;
*
*/
@PropertySource(value = {"classpath:person.properties"})
@Component
@ConfigurationProperties(prefix = "person")
@ImportResource:导入Spring的配置文件,让配置文件里面的内容生效
想让Spring的配置文件生效,加载进来,@ImportResource标注在一个配置类上
@ImportResource(locations = {"classpath: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="com.shinb.demo.service.HelloService"></bean>
</beans>
SpringBoot不推荐通过导入配置文件添加组件,推荐使用全注解方式
- 创建配置类@Configuration ----> Spring配置文件
- 在配置类使用@Bean给容器中添加组件
/**
* @Configuration 指明当前类是一个配置类;就是来替代之前的Spring配置文件
* @Bean 等同于<bean><bean/>
*/
public class MyDemoConfig {
@Bean
public HelloService getHelloService(){
return new HelloService();
}
}
3、Profile
1、多profile文件
我们在主配置文件编写的时候,文件名格式可以是 application-{profile}.properties/yml 默认使用application.properties的配置
- application.yml
- application-dev.yml
- application-proc.yml
- application-uat.yml
2、指定profile
在配置文件中指定 spring.profiles.active=dev
spring:
profiles:
active: dev
命令行
java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar --spring.profiles.active=dev
JVM参数
-Dspring.profiles.active=dev
3、配置文件位置
springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的默认配置文件,优先级由高到底,高优先级的配置会覆盖低优先级的配置。
- –file:./config/
- –file:./
- –classpath:/config/
- –classpath:/
SpringBoot会从这四个位置全部加载主配置文件;互补配置
我们还可以通过spring.config.location来改变默认的配置文件位置,项目打包好以后,我们可以使用命令行参数的形式,启动项目的时候来指定配置文件的新位置,指定配置文件和默认加载的这些配置文件共同起作用形成互补配置。
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar -- spring.config.location=G:/application.properties
4、外部配置
1.命令行参数,所有的配置都可以在命令行上进行指定
java -jar spring-boot-02-config-02-0.0.1-SNAPSHOT.jar --server.port=8087 --server.context-path=/abc
多个配置用空格分开; --配置项=值
2.来自java:comp/env的JNDI属性
3.Java系统属性(System.getProperties())
4.操作系统环境变量
5.RandomValuePropertySource配置的random.*属性值 由jar包外向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指定的默认属性
5、自动配置
1、自动配置原理
1)SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration
2)@EnableAutoConfiguration 作用
- 利用EnableAutoConfigurationImportSelector给容器中导入一些组件;
- 可以查看selectImports()方法的内容;
- List configurations = getCandidateConfigurations(annotationMetadata, attributes);获取候选的配置
SpringFactoriesLoader.loadFactoryNames()
扫描所有jar包类路径下META‐INF/spring.factories
把扫描到的这些文件的内容包装成properties对象
从properties中获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加在容器中
将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration的值加入到了容器中,每一个这样的 xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中,用他们来做自动配置
3)以HttpEncodingAutoConfiguration(Http编码自动配置)为例解释自动配置原理
@Configuration(
proxyBeanMethods = false
) //表示这是一个配置类,以前编写的配置文件一样,也可以给容器中添加组件
@EnableConfigurationProperties({ServerProperties.class}) //启动指定类的
//ConfigurationProperties功能;将配置文件中对应的值和ServerProperties绑定起来;并把ServerProperties加入到ioc容器中
@ConditionalOnWebApplication(
type = Type.SERVLET
)//Spring底层@Conditional注解(Spring注解版),根据不同的条件
//如果满足指定的条件,整个配置类里面的配置就会生效;判断当前应用是否是web应用,如果是,当前配置类生效
@ConditionalOnClass({CharacterEncodingFilter.class}) //判断当前项目有没有这个类
CharacterEncodingFilter;SpringMVC中进行乱码解决的过滤器
@ConditionalOnProperty(
prefix = "server.servlet.encoding",
value = {"enabled"},
matchIfMissing = true
) //判断配置文件中是否存在某个配置 spring.http.encoding.enabled;如果不存在,判断也是成立的
//即使我们配置文件中不配置pring.http.encoding.enabled=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;
}
根据当前不同的条件判断,决定这个配置类是否生效, 一但这个配置类生效;这个配置类就会给容器中添加各种组件;这些组件的属性是从对应的properties类中获取 的,这些类里面的每一个属性又是和配置文件绑定的;
4)所有在配置文件中能配置的属性都是在xxxxProperties类中封装者‘;配置文件能配置什么就可以参照某个功 能对应的这个属性类
@ConfigurationProperties(
prefix = "server",
ignoreUnknownFields = true
)//从配置文件中获取指定的值和bean的属性进行绑定
public class ServerProperties {
总结:
- SpringBoot启动会加载大量的自动配置类
- 我们看我们需要的功能有没有SpringBoot默认写好的自动配置类;
- 我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件有,我们就不需要再来配置了)
- 给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们就可以在配置文件中指定这些属性的值;
xxxxAutoConfigurartion:自动配置类; 给容器中添加组件
xxxxProperties:封装配置文件中相关属性;
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存在指定项 |