一、为什么需要加载局部配置文件
使用 @Value 或 @ConfigurationProperties 为属性注入配置文件中的值时,默认是去全局配置文件(application.properties 或 application.yml)去寻找对应的值。
但是如果都将配置放入该文件,不方便找到,所以可以使用局部配置文件。
在类上使用 @PropertySource 指定对应的局部配置文件,即可读入局部配置文件的配置。
@PropertySource(value = {
"配置文件位置"})
可同时制定多个配置文件,在 {} 中使用逗号(,)隔开即可。
二、加载局部配置文件示范
1、新建局部配置文件
在 src/main/resources 下新建局部配置文件 demo.properties
# 配置 demo 的值
demo.last-name=lisi
demo.age=30
demo.birthday=1989/9/12
demo.boss=false
demo.salary=23000
demo.map.key1=value1
demo.map.key2=value2
demo.list=one, two, three
demo.data-demo.name=zhangsan
demo.data-demo.age=20
2、在类上加上 @PropertySource,并指定局部配置文件的位置
package com.example.springbootboot02config.bean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @author liyanan
* @date 2019/12/16 13:43
*/
@PropertySource