SpringBoot @PropertySource注解使用


一. 使用场景

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;
}

四. 效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值