SpringBoot注解 @Configuration @PropertySource @ConfigurationProperties

@Configuration

@PropertySource

@ConfigurationProperties

三者经常搭配使用在 SpringBoot 项目中的 Java 配置类上。

1、@Configuration 表明该类为一个配置类

2、@PropertySource(value = "classpath: export.properties", encoding = "utf-8")

如果export.properties文件中有中文,可以通过设置encoding属性解决中文乱码问题

3、@ConfigurationProperties(prefix="book.service.export")

指定前缀,可以设置属性文件的key与配置类中的属性的对应关系

这样对配置类中的属性的命名比较严格,必须与配置文件中的key一致,否则对应不上。

一个很简单的例子:

@Configuration
@PropertySource(value = "classpath:export.properties", encoding = "utf-8")
@ConfigurationProperties(prefix = "book.service.export")
public class ExportConfiguration {

    private String name;
    getter 方法
    setter 方法

}

配置文件中键值对:

book.service.export.name=alice

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/109343690