SpringBoot读取配置文件
(1)添加pom依赖
1 <!-- 添加这个配置文件处理器,编写配置文件就有智能提示功能了--> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-configuration-processor</artifactId> 5 <optional>true</optional> 6 </dependency>
(2)编写配置文件
1 2 3 4 | user.id=1 user.userName=fanqi user.passWord=fanqi user.enabled=1 |
(3)编写配置文件
1 package cn.coreqi.entities; 2 3 import org.springframework.beans.factory.annotation.Value; 4 import org.springframework.boot.context.properties.ConfigurationProperties; 5 import org.springframework.context.annotation.PropertySource; 6 import org.springframework.stereotype.Component; 7 8 @Component 9 @ConfigurationProperties(prefix = "user") 10 @PropertySource(value = {"classpath:user.properties"}) //加载指定的Properties配置文件(不支持yml文件) 11 public class User { 12 //@Value("${user.id}") 13 private Integer id; 14 //@Value("${user.userName}") 15 private String userName; 16 //@Value("${user.passWord}") 17 private String passWord; 18 //@Value("${user.enabled}") 19 private Integer enabled; 20 21 public User() { 22 } 23 24 public User(Integer id, String userName, String passWord, Integer enabled) { 25 this.id = id; 26 this.userName = userName; 27 this.passWord = passWord; 28 this.enabled = enabled; 29 } 30 31 public Integer getId() { 32 return id; 33 } 34 35 public void setId(Integer id) { 36 this.id = id; 37 } 38 39 public String getUserName() { 40 return userName; 41 } 42 43 public void setUserName(String userName) { 44 this.userName = userName; 45 } 46 47 public String getPassWord() { 48 return passWord; 49 } 50 51 public void setPassWord(String passWord) { 52 this.passWord = passWord; 53 } 54 55 public Integer getEnabled() { 56 return enabled; 57 } 58 59 public void setEnabled(Integer enabled) { 60 this.enabled = enabled; 61 } 62 63 @Override 64 public String toString() { 65 return "User{" + 66 "id=" + id + 67 ", userName='" + userName + '\'' + 68 ", passWord='" + passWord + '\'' + 69 ", enabled=" + enabled + 70 '}'; 71 } 72 }
功能 | @ConfigurationProperties | @Value |
松散绑定(类属性和配置文件中属性是否一致) | 支持(驼峰式、下划式等切换) | 不支持 |
Spring EL 表达式 | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |
复杂类型(如Map等) | 支持 | 不支持 |
使用场景 | 批量注入配置文件中的属性 | 单个指定 |
* Idea解决properties文件乱码问题
作者:奇
出处:https://www.cnblogs.com/fanqisoft/p/10321245.html
版权:本作品采用「本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。」许可协议进行许可。
分类:
Spring Boot
如果文章内容对您有所帮助,欢迎赞赏.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!