Spring Boot最常用的3种读取properties配置文件中数据的方法:
1. 使用@Value注解读取
读取properties配置文件时,默认读取的是application.properties。
application.properties:
demo.name=Name
demo.age=18
Java代码:
import
运行结果如下:
这里,如果要把
@Value
部分放到一个单独的类A中进行读取,然后在类B中调用,则要把类A增加@Component注解,并在类B中使用@Autowired自动装配类A,代码如下。
类A:
import
类B:
import
运行结果如下:
注意:如果@Value${}所包含的键名在application.properties配置文件中不存在的话,会抛出异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'demo.name' in value "${demo.name}"
2. 使用Environment读取
application.properties:
demo.sex=男
demo.address=山东
Java代码:
import
运行,发现中文乱码:
这里,我们在application.properties做如下配置:
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
然后修改IntelliJ IDEA,File --> Settings --> Editor --> File Encodings ,将最下方Default encoding for properties files设置为UTF-8,并勾选Transparent native-to-ascii conversion。
重新运行结果如下:
3. 使用@ConfigurationProperties注解读取
在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。
在srcmainresources下新建config.properties配置文件:
demo.phone=10086
demo.wife=self
创建ConfigBeanProp并注入config.properties中的值:
import
- @Component 表示将该类标识为Bean
- @ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。
- @PropertySource(value = "config.properties")表示配置文件路径。
使用时,先使用@Autowired自动装载ConfigBeanProp,然后再进行取值,示例如下:
import
运行结果如下:
GitHub:
dkbnull/SpringBootDemogithub.comCSDN:
https://blog.csdn.net/dkbnull/article/details/81953190blog.csdn.net微信:
https://mp.weixin.qq.com/s/swtkNq6CLMsP4uc4PgaVHgmp.weixin.qq.com微博:
Spring Boot入门:读取properties配置文件中的数据weibo.com