Spring Boot 获取properties中定义的属性值
常规属性配置
1.在application.properties中定义自定义属性
2.修改入口类
3.运行,浏览器访问
http://localhost:9992/
类型安全的配置(基于properties)
使用@Value注入配置在实际项目中比较麻烦,配置个数比较多,需要使用@Vlaue注入很多次。
Spring Boot还提供了基于类型安全的配置方式,通过@ConfigurationProperties将properties属性和一个Bean及其属性关联,实现类型安装的配置。
1.在pom中引入
org.springframework.boot
spring-boot-configuration-processor
true
idea提示文档
https://docs.spring.io/spring-boot/docs/1.5.8.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor
2.创建custom.properties并定义属性
3.创建Bean
在1.5版本之前配置是
@ConfigurationProperties(prefix = “custom.prop”,location=“classpath:custom.properties”)
但是我现在使用的新版本1.5.8
需要@PropertySource(“classpath:custom.properties”) //指定自定义的资源目录
4.修改入口类,通过@Autowired注入配置
5.运行访问http://localhost:9992/
原文链接:https://www.jianshu.com/p/4b9c5c9e24fc