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默认文件编码格式
3.4、@Value和@ConfigurationProperties获取值的区别
总结:
如果只是需要配置文件中的某个属性,建议使用 @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配置文件
*/
@Conf