笔记
spring boot 允许使用properties、yaml文件或者命令行参数作为外部支持配置
根据习惯,一般用propweties文件
spring boot里已存在一个application.properties可以直接在里面增加属性如:
App.name
App.author
在类中注入
application.propertie文件属性值只需在属性前加上@Value即可如:
@Value("${App.name}")
private String appName;
@Value("${App.author}")
private String appAuthor;
所以我们可以使用@ConfigurationProperties注解来加载我们的配置文件,并通过添加参数来指定我们要注入的属性前缀,我们在创建实体类属性的时候,只需保证类属性名与前缀后面的属性名一致即可。
如:
application.properties中:
book.name=abc
book.author=cba
Bean中:
@Component
@ConfigurationProperties(prefix = "book")
public class BookSettings{
private String name;
private String author;
//getter和setter方法省略未显示。如果使用@ConfigurationProperties是必须要使用getter和setter的
}
如果有多个properties文件存在,同样可以使用@ConfigurationProperties注解来加载指定配置文件
@ConfigurationProperties(prefix = "book",locations = {"classpath:book.properties"})
//book.properties文件在/src/main/resources目录下
(locations为空时则加载默认配置文件
application.properties)