SpringBoot使用@PropertySource读取 properties 配置

SpringBoot使用@PropertySource读取 properties 配置

properties配置文件

在resources文件夹下,新建一个文件 property-demo.properties,

示例如下:

my.config.test.name=wu

my.config.test.id=123

配置的类

@PropertySource 指定配置文件。
classpath: 表示会到 target下面的class路径中查找找文件。

@Data 是 lombok 依赖包的注解,主要是用来表示 getter、 setter。

@ConfigurationProperties的 prefix 指定配置的前缀 my.config.test,比如 my.config.test.name, 就对应此类的 name属性。

/**
 * ConfigurationProperties的 prefix 指定配置的前缀 my.config.test,
 * properties文件配置的 my.config.test.name,就对应此类的 name属性。
 *
 */
@ConfigurationProperties(prefix = "my.config.test")
@PropertySource(value = "classpath:property-demo.properties",encoding = "UTF-8")
@Data
@Component
public class MyPropertySourceConfig {


    private String name;

    private Integer id;

}

测试代码:

    @Resource
    private MyPropertySourceConfig myPropertySourceConfig;


    @Test
    public void getProperty() {
        String name = myPropertySourceConfig.getName();
        System.out.println("name: " + name);
        Assert.assertNotNull(name);
    }

参考资料:

https://blog.csdn.net/lzb348110175/article/details/105147070/

posted on   乐之者v  阅读(380)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2022-07-11 Intellij Idea的数据库工具 DataGrip
2018-07-11 如何阅读一个Web项目 【转载】
< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示