目录
一. 使用场景
Spring默认会读取resources文件夹下的名称为application
的配置文件.如果配置文件命名不是application,则无法读取.此时可以使用@PropertySource
注解进行读取.
@PropertySource
注解只能读取后缀为.properties
的配置文件,yaml
是无法读取的.
二. 配置
在resources文件夹下新建一个commonConfig文件夹,然后新建common.properties
配置文件
common.name=FengYeHong
common.age=18
# List
common.categorys=red,blue,white
# Map
common.personInfo={"id": "110120", "address": "地球"}
三. 读取自定义配置文件
3.1 方式1: @PropertySource + @Value
- 可以使用Spel表达式
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
import java.util.Map;
@Configuration
// 读取resources下commonConfig文件夹下的自定义配置文件
@PropertySource(value = {"commonConfig/common.properties"})
@Data
public class CommonConfig1 {
@Value("${common.name}")
private String name;
@Value("${common.age}")
private int age;
/**
* 使用SpEL表达式将 common.properties 配置文件中的配置转换为List
* common.categorys: 中的 : 是为了common.categorys不存在的时候,指定默认值.防止程序解析储出错
*/
@Value("#{'${common.categorys:}'.split(',')}")
private List<String> categoryList;
// 使用SpEL表达式,将配置信息解析为map
@Value("#{${common.personInfo}}")
private Map<String,String> personInfoMap;
}
3.2 方式2: @PropertySource + @ConfigurationProperties
- 因为没有@Value注解,因为无法使用Spel表达式
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import java.util.List;
@Configuration
@PropertySource(value = {"commonConfig/common.properties"})
@ConfigurationProperties(prefix = "common")
@Data
public class CommonConfig2 {
private String name;
private int age;
}