Chapter2 : SpringBoot配置

尚硅谷SpringBoot顶尖教程

1. 全局配置文件

SpringBoot使用一个全局的配置文件 application.properties 或者 application.yml ,该配置文件放在src/main/resources目录或者类路径/config目录下面, 可以用来修改SpringBoot自动配置的默认值。

yml是YAML(YAML Ain’t Markup Language)语言的文件,参考规范http://www.yaml.org/

以前的配置文件, 大多都是使用xml文件, 比较繁重; yml则以数据为中心, 比json,xml更适合做配置文件。

2. yaml语法

2.1 基本语法

key: (空格) value 表示一对键值对儿(空格必须有)

以空格的缩进来控制层级关系;只要是左对齐的一列数据,都是同一个层级。属性和值是大小写敏感的。

server:
  port: 8084

2.2 值的写法

字面量: 普通的值(数字,布尔值,字符串)。字符串不用加单引号或者双引号。

双引号:不会转义字符串里面的特殊字符,特殊字符会作为本身意义表示。

name: "zhangsan \n lisi"
输出: 
zhangsan
lisi

单引号:会转义特殊字符,特殊字符最终只是一个普通的字符串数据。

name: 'zhangsan \n lisi'
输出: 
zhangsan \n lisi

对象、Map(属性和值)

对象还是key: value的形式。在下一行来写对象的属性和值,注意缩进。例如对象friends:

friends:
	lastName: zhangsan
	age: 20

对象还有行内写法:

friends: {lastName: zhangsan, age: 18}

数组(List、Set)

-值表示数组中的一个元素

animals:
	- cat
	- dog
	- pig

数组也有行内写法:

animals: [cat,dog,pig]

3. 配置文件值注入

3.1 @ ConfigurationProperties注入

配置文件配置内容如下:

person:
  age: 18
  boss: false
  birth: 2017/12/12
  maps: {k1: v1,k2: v2}
  lists:
    - lisi
    - wanwu
  dog:
    name: 旺财
    age: 2
  last-name: zhangsan

JavaBean, 注意Person类要写setXXX()方法才会注入成功。

@Component
@ConfigurationProperties(prefix = "person")  // 优先级高于@value
public class Person implements Serializable {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    // getXXX setXXX
}

我们可以导入配置文件处理器,以后编写配置就有提示。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

yml书写效果:
在这里插入图片描述
properties文件书写效果:
在这里插入图片描述

测试结果:

Person{lastName='zhangsan', age=18, boss=false, birth=Tue Dec 12 00:00:00 CST 2017, maps={k1=v1, k2=v2}, lists=[lisi, wanwu, cat]], dog=Dog{name='旺财', age=2}}

3.2 中文乱码问题

yml或properties配置文件的参数配置为中文值,注入出现乱码问题。
在这里插入图片描述
修改系统默认配置文件的编码
在这里插入图片描述

3.3 @Value注入

JavaBean

@Component
public class Person implements Serializable {
    @Value("${person.last-name}")
    private String lastName;
    @Value("#{10*2}")
    private Integer age;
    @Value("true")
    private Boolean boss;
    private Date birth;
    // @Value不支持复杂类型
//    @Value("${person.maps}")
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    // getXXX setXXX
}

测试结果:

Person{lastName='zhangsan', age=20, boss=true, birth=null, maps=null, lists=null, dog=null}

@ ConfigurationProperties优先级高于@Value

3.4 @ ConfigurationProperties结合@PropertySource

如果不想将person属性配置在全局配置文件(properties或yaml)中, 可以放到自定义的properties文件中。

自定义person.properties文件

person.last-name=张胜男${random.uuid}
person.age=${random.int}
person.birth=2017/12/15
person.boss=false
person.maps.k1=v1
person.maps.k2=v2
person.lists=[pig,dog,cat]
person.dog.name=旺财-${person.last-name}-${person.hello:hello}
person.dog.age=2

在JavaBean类上使用@PropertySource引入自定义的properties文件。

@Component
@PropertySource(value = {"classpath:person.properties"})
@ConfigurationProperties(prefix = "person")  // 优先级高于@value
public class Person implements Serializable {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    // getXXX setXXX
}

测试结果:

Person{lastName='张胜男6eea5415-7d81-41a1-95be-bf72dba5b839', age=-298203675, boss=false, birth=Fri Dec 15 00:00:00 CST 2017, maps={k1=v1, k2=v2}, lists=[[pig, dog, cat]], dog=Dog{name='旺财-张胜男c650e5a0-791f-4f39-9d4f-1bea2d7527bf-hello', age=2}}

3.5 @ ConfigurationProperties结合@Bean

@ ConfigurationProperties结合@Bean可以为属性赋值 。

JavaBean

public class Dog {
    private String name;
    private Integer age;
    // getXXX , setXXX
}    

在全局配置文件yaml中配置dog对象的属性值。

dog:
  name: 旺财
  age: 2

在主启动类或配置类中使用@ ConfigurationProperties结合@Bean声明dog实例并给属性赋值。

@Bean
@ConfigurationProperties(prefix = "dog")
public Dog dog() {
    return new Dog();
}

测试结果:

Dog{name='旺财', age=2}

3.6 JSR303校验

@ConfigurationProperties结合@Validated注解支持JSR303进行配置文件属性值的校验。

pom.xml文件中需要加入相关依赖,尤其是验证依赖的实现类。

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.2.4.Final</version>
</dependency>

JavaBean

package com.atgugui.bean;
import org.springframework.validation.annotation.Validated;
// ....省略导入
@Component
@ConfigurationProperties(prefix = "person")  // 优先级高于@value
@Validated
public class Person implements Serializable {
    @Null // lastName必须为空
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<Object> lists;
    private Dog dog;
    // getXXX setXXX
}

启动应用报错,测试结果:

Property: person.lastName
    Value: 张胜男562391e3-b84a-4d4d-ad9e-3d0322d67e94
    Reason: 必须为null

3.7 @Value和@ ConfigurationProperties比较

功能批量注入配置文件中的属性一个个指定
松散绑定(松散语法)支持不支持
SpEL不支持支持
JSR303数据校验支持不支持
复杂类型封装支持不支持

如果我们只是在某个业务逻辑中需要获取一下配置文件中的某项值,就用@Value

4. @ImportResource

读取外部配置文件,导入Spring的配置文件,让配置文件里面的内容生效。在对SSM老项目进行架构升级时可以在配置类中使用该注解将原来xml配置中的Bean维护到IOC容器中,实现与SpringBoot兼容的效果。

编写xml配置 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="helloServiceBean" class="com.atgugui.service.HelloServiceBean"/>
</beans>

编写test测试模拟:

@SpringBootTest
@RunWith(SpringRunner.class)
class SpringBoot01HelloQuickApplicationTests {
    @Autowired
    ApplicationContext ioc;
    @Test
    public void testHelloService() {
         boolean helloServiceBean = ioc.containsBean("helloServiceBean");
       System.out.println(MessageFormat.format("contains helloServiceBean: {0}", helloServiceBean));
    }
}

没使用@ImportResouce注解的测试结果:

contains helloServiceBean: false

SpringBoot里面没有Spring的xml配置文件,我们自己编写的xml配置文件也不能自动识别。想让Spring的xml配置文件加载生效,使用@ImportResource注解。可以在主启动类添加 @ImportResource注解,指定要加载的xml配置。

@SpringBootApplication 
@ImportResource(locations = {"classpath:beans.xml"})
public class SpringBoot01HelloQuickApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringBoot01HelloQuickApplication.class, args);
    }
}

使用@ImportResouce注解的测试结果:

contains helloServiceBean: true

当然,SpringBoot推荐使用JavaConfig配置类的方式给容器中添加组件,不编写xml配置。

不需要编写xml配置,改用配置类实现Spring配置文件:

@Configuration
public class MyAppConfig {
    // 将方法的返回值添加到容器中,容器中这个组件默认的id就是方法名
    @Bean
    public HelloServiceBean helloServiceBean() {
        System.out.println("配置类@Bean给容器中添加HelloServiceBean组件");
        return new HelloServiceBean();
    }
}

测试结果:

配置类@Bean给容器中添加HelloServiceBean组件
contains helloServiceBean: true

5. 配置文件占位符

5.1 随机数

RandomValuePropertySource 配置文件中可以使用随机数。
在这里插入图片描述

5.2 属性配置占位符

  • 可以在配置文件中引用前面配置过的属性。
  • ${person.hello:默认值} 来指定找不到属性时的默认值。

编写占位符配置:

person.last-name=张胜男${random.uuid}
person.age=${random.int}
person.dog.name=旺财-${person.last-name}-${person.hello:hello}

打印person测试结果:

Person{lastName='张胜男80eae444-2550-442c-b657-f5f6704794a3', age=1952295864, boss=false, birth=Fri Dec 15 00:00:00 CST 2017, maps={k1=v1, k2=v2}, lists=[[pig, dog, cat]], 
       // 读取到上面的person.last-name 	${person.hello}没有就使用指定的默认值hello
dog=Dog{name='旺财-张胜男91918168-7841-41ce-9359-7129d6a866cd-hello', age=2}}

6. Profile

6.1 多profile文件形式

格式:application-{profile}.properties
application-dev.properties , application-prod.properties
然后在默认配置文件application.properties中指定加载哪个环境的配置文件:

#指定加载dev环境配置
spring.profiles.active=dev
#指定加载prod环境配置
#spring.profiles.active=prod

6.2 yml支持多profile文档块形式

使用三个短横线分割多个profile文档块,然后通过spring.profiles.active=${profile}指定加载哪个环境的配置。

spring:
  profiles:
    active: prod
---
server:
  port: 8081
spring:
  profiles: dev

---
server:
  port: 8084
spring:
  profiles: prod

6.3 profile激活方式

可以在全局配置文件中指定: spring.profiles.active=dev

也可以在在命令行指定: --spring.profiles.active=dev

如果执行jar包也可以指定环境配置: java -jar xxx.jar --spring.profiles.active=dev
在这里插入图片描述

jvm参数指定配置环境 : -Dspring.profiles.active=dev
在这里插入图片描述

系统环境变量也可以指定
在这里插入图片描述

7. 配置文件加载位置

Spring Boot启动会扫描以下位置的application.properties或者application.yml文件作为SpringBoot的默认配置文件。

  • file:./config/

  • file:./

  • classpath:/config/

  • classpath:/

以上都是按照优先级从高到低的顺序,所有位置的文件都会被加载,高优先级配置内容会覆盖低优先级配置内容。SpringBoot会从这四个位置全部加载主配置文件,互补配置。我们也可以通过配置spring.config.location来改变默认配置。

java -jar xxx.jar --spring.config.location=D:\\application.properties

8. 外部配置加载顺序

SpringBoot支持多种外部配置方式,可以从以下位置加载配置。优先级从高到低,高优先级的配置会覆盖低优先级的配置,所有的配置会形成互补配置。

  • 命令行参数, 多个参数配置用空格分开:
java -jar xxx.jar --server.port=8082 --server.context-path=/abc
  • 来自java:comp/env的JNDI属性
  • Java系统属性(System.getProperties())
  • 操作系统环境变量

jar包外jar包内寻找,优先加载带profile的配置

  • jar包外部的application-{profile}.properties或application-{profile}.yml(带spring.profile)配置文件。

  • jar包内部的application-{profile}.properties或application-{profile}.yml(带spring.profile)配置文件。

  • jar包外部的application-{profile}.properties或application-{profile}.yml(不带spring.profile)配置文件。

  • jar包内部的application-{profile}.properties或application-{profile}.yml(不带spring.profile)配置文件。

  • @Configuration注解类上的@PropertySource

  • 通过SpringApplication.setDefaultProperties指定的默认属性。
    参考官方资料: https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#boot-features-external-config

9. 自动配置原理

9.1 剖析源码

  • SpringBoot启动的时候加载主配置类,开启了自动配置功能 @EnableAutoConfiguration

  • @EnableAutoConfiguration作用:
    利用AutoConfigurationImportSelector给容器导入一些组件。
    可以导入selectImport()方法的内容,通过下面的方法获取候选的配置。

    AutoConfigurationImportSelector#selectImports

    @Override
    	public String[] selectImports(AnnotationMetadata annotationMetadata) {
    		if (!isEnabled(annotationMetadata)) {
    			return NO_IMPORTS;
    		}
    		try {
    			// ...
                // 获取候选的配置
    			List<String> configurations = getCandidateConfigurations(annotationMetadata,
    					attributes);
    			// ....
    		}
    		catch (IOException ex) {
    			throw new IllegalStateException(ex);
    		}
    	}
    

    AutoConfigurationImportSelector#getCandidateConfigurations

    protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
    			AnnotationAttributes attributes) {
        // SpringFactoriesLoader加载META-INF/spring.factories文件配置
    		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
               // getSpringFactoriesLoaderFactoryClass()=EnableAutoConfiguration.class
    				getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
    		Assert.notEmpty(configurations,
    				"No auto configuration classes found in META-INF/spring.factories. If you "
    						+ "are using a custom packaging, make sure that file is correct.");
    		return configurations;
    }
    

    AutoConfigurationImportSelector#getSpringFactoriesLoaderFactoryClass

    protected Class<?> getSpringFactoriesLoaderFactoryClass() {
    	return EnableAutoConfiguration.class;
    }
    

    SpringFactoriesLoader#loadFactoryNames(…) 扫描所有jar包类路径下META-INF/spring.factories,把扫描到的这些文件内容包装成Properties对象。

    从properties中获取EnableAutoConfiguration.class类对应的值,然后把它们加载到容器中。

    将类路径下META-INF/spring.factories里面配置的所有EnableAutoConfiguration.class类对应的值加入到容器中。

    public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {
        	// EnableAutoConfiguration.class.getName()=EnableAutoConfiguration
    		String factoryClassName = factoryClass.getName();
    		try {
                // FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories"
    			Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
    					ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
                // 存放解析后的候选配置
    			List<String> result = new ArrayList<String>();
    			while (urls.hasMoreElements()) {
    				URL url = urls.nextElement();
                    // 将解析的组件封装到properties对象中
    				Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));
    				String factoryClassNames = properties.getProperty(factoryClassName);
    				result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));
    			}
    			return result;
    		}
    		catch (IOException ex) {
    			throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() +
    					"] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);
    		}
    	}
    

    下图中每一个这样的xxxAutoConfiguration类都是容器中的一个组件,都加入到容器中进行自动配置。
    在这里插入图片描述

9.2 案例分析

HttpEncodingAutoConfiguration为例解释自动配置原理

// 表示这是一个配置类,相当于以前的xml配置
@Configuration
// 启动指定配置类的属性配置绑定
@EnableConfigurationProperties(HttpEncodingProperties.class)
// Spring底层@Conditional注解根据不同的条件, 以及是否满足指定的条件来控制整个配置类里面的配置是否生效
@ConditionalOnWebApplication // 判断当前应用是否是web应用, 如果是web应用则生效
// 判断当前项目有没有指定的类, 如果有则生效
@ConditionalOnClass(CharacterEncodingFilter.class) // SpringMVC中解决乱码问题的过滤器
// 判断配置文件中是否存在某个配置属性,matchIfMissing=true 如果判断不存在默认也成立并生效
@ConditionalOnProperty(prefix = "spring.http.encoding", value = "enabled", matchIfMissing = true)
public class HttpEncodingAutoConfiguration {
	// 与SpringBoot项目的全局配置文件application.properties建立映射关系
	private final HttpEncodingProperties properties;
	// 只有一个有参构造器时, 参数的属性值就会从容器中获取
	public HttpEncodingAutoConfiguration(HttpEncodingProperties properties) {
		this.properties = properties;
	}

    
	@Bean
	// 给容器中添加一个组件,该组件的某些属性值要从this.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类中获取的,这些类里面的每一个属性又是和配置文件绑定的。

所有在配置文件中能配置的属性是在xxxProperties类中封装着,配置文件能配置什么就可以参照某个功能对应的这个属性类。

#我们能配置的属性都是来源于这个功能的properties类
spring.http.encoding.enabled=true
spring.http.encoding.charset=utf-8
spring.http.encoding.force=true

将SpringBoot项目全局配置文件中spring.http.encoding前缀的属性值绑定并填充到HttpEncodingProperties中.

实现属性值的绑定读取需要在启动类或配置类上添加@EnableConfigurationProperties注解开启属性绑定配置。

@ConfigurationProperties(prefix = "spring.http.encoding")
public class HttpEncodingProperties {
    //...
}

9.3 Conditional派生注解

@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环境
@ConditionalOnJndiJNDI存在指定项

自动配置类必须在一定的条件下才能生效。我们如何知道哪些自动配置类生效。可以通过在全局配置文件application.properties文件中配置SpringBoot的debug模式,来让控制台打印自动配置报告,从而查看哪些自动配置类生效。

#开启SpringBoot的debug模式
debug=true

查看SpringBoot项目启动日志:

匹配上且生效的自动配置类

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)

   DispatcherServletAutoConfiguration.DispatcherServletConfiguration matched:
      - @ConditionalOnClass found required class 'javax.servlet.ServletRegistration'; @ConditionalOnMissingClass did not find unwanted class (OnClassCondition)
      - Default DispatcherServlet did not find dispatcher servlet beans (DispatcherServletAutoConfiguration.DefaultDispatcherServletCondition)
  // ........

没有生效的自动配置类

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' (OnClassCondition)
  // ..............  
2023-03-12 20:45:19.142  INFO 21220 --- [           main] c.a.SpringBoot01HelloQuickApplication    : Started SpringBoot01HelloQuickApplication in 2.672 seconds (JVM running for 4.087)  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值