SpringBoot使用@PropertySource读取 properties 配置

发布时间 2023-07-11 14:04:29作者: 乐之者v

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/