• 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": "地球"}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    三. 读取自定义配置文件

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    四. 效果

    在这里插入图片描述

  • 相关阅读:
    PHP开发工具:打造高效的编码体验
    PG大小版本升级步骤
    LeetCode01
    Linux平台如何实现采集音视频数据并注入轻量级RTSP服务?
    TRex学习之旅十一
    【Golang】使用代码绘制图表的开源库对比
    Linux打包和使用动静态库
    Linux一键安装K8s集群
    c# List vs SortedList vs LinkedList
    EMNLP-21-Exploring Task Difficulty for Few-Shot Relation Extraction
  • 原文地址:https://blog.csdn.net/feyehong/article/details/126675202