Springboot优雅读配置文件
转载自Springboot优雅读配置文件
很多时候我们需要将一些常用的配置信息比如阿里云oss配置、发送短信的相关信息配置等等放到配置文件中。
下面我们来看一下 Spring 为我们提供了哪些方式帮助我们从配置文件中读取这些配置信息。
application.yml 内容如下:
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重,但是,我相信一切都会过去!武汉加油!中国加油!
my-profile:
name: Guide哥
email: koushuangbwcx@163.com
library:
location: 湖北武汉加油中国加油
books:
- name: 天才基本法
description: 二十二岁的林朝夕在父亲确诊阿尔茨海默病这天,得知自己暗恋多年的校园男神裴之即将出国深造的消息——对方考取的学校,恰是父亲当年为她放弃的那所。
- name: 时间的秩序
description: 为什么我们记得过去,而非未来?时间“流逝”意味着什么?是我们存在于时间之内,还是时间存在于我们之中?卡洛·罗韦利用诗意的文字,邀请我们思考这一亘古难题——时间的本质。
- name: 了不起的我
description: 如何养成一个新习惯?如何让心智变得更成熟?如何拥有高质量的关系? 如何走出人生的艰难时刻?
1.通过 @value 读取比较简单的配置信息
使用 @Value("${property}") 读取比较简单的配置信息:
@Value("${wuhan2020}")
String wuhan2020;
需要注意的是
@value这种方式是不被推荐的,Spring 比较建议的是下面几种读取配置信息的方式。
2.通过@ConfigurationProperties读取并与 bean 绑定
LibraryProperties类上加了@Component注解,我们可以像使用普通 bean 一样将其注入到类中使用。
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
@ConfigurationProperties(prefix = "library")
@Setter
@Getter
@ToString
class LibraryProperties {
private String location;
private List<Book> books;
@Setter
@Getter
@ToString
static class Book {
String name;
String description;
}
}
这个时候你就可以像使用普通 bean 一样,将其注入到类中使用:
package cn.javaguide.readconfigproperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author shuang.kou
*/
@SpringBootApplication
public class ReadConfigPropertiesApplication implements InitializingBean {
private final LibraryProperties library;
public ReadConfigPropertiesApplication(LibraryProperties library) {
this.library = library;
}
public static void main(String[] args) {
SpringApplication.run(ReadConfigPropertiesApplication.class, args);
}
@Override
public void afterPropertiesSet() {
System.out.println(library.getLocation());
System.out.println(library.getBooks()); }
}
控制台输出:
湖北武汉加油中国加油
[LibraryProperties.Book(name=天才基本法, description........]
3.通过@ConfigurationProperties读取并校验
我们先将application.yml修改为如下内容,明显看出这不是一个正确的 email 格式:
my-profile:
name: Guide哥
email: koushuangbwcx@
ProfileProperties类没有加@Component注解。我们在我们要使用ProfileProperties的地方使用@EnableConfigurationProperties注册我们的配置bean:
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotEmpty;
/**
* @author shuang.kou
*/
@Getter
@Setter
@ToString
@ConfigurationProperties("my-profile")
@Validated
public class ProfileProperties {
@NotEmpty
private String name;
@Email
@NotEmpty
private String email;
//配置文件中没有读取到的话就用默认值
private Boolean handsome = Boolean.TRUE;
}
具体使用:
package cn.javaguide.readconfigproperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* @author shuang.kou
*/
@SpringBootApplication
@EnableConfigurationProperties(ProfileProperties.class)
public class ReadConfigPropertiesApplication implements InitializingBean {
private final ProfileProperties profileProperties;
public ReadConfigPropertiesApplication(ProfileProperties profileProperties) {
this.profileProperties = profileProperties;
}
public static void main(String[] args) {
SpringApplication.run(ReadConfigPropertiesApplication.class, args);
}
@Override
public void afterPropertiesSet() {
System.out.println(profileProperties.toString());
}
}
因为我们的邮箱格式不正确,所以程序运行的时候就报错,根本运行不起来,保证了数据类型的安全性:
Binding to target org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'my-profile' to cn.javaguide.readconfigproperties.ProfileProperties failed:
Property: my-profile.email
Value: koushuangbwcx@
Origin: class path resource [application.yml]:5:10
Reason: must be a well-formed email address
我们把邮箱测试改为正确的之后再运行,控制台就能成功打印出读取到的信息:
ProfileProperties(name=Guide哥, email=koushuangbwcx@163.com, handsome=true)
4.@PropertySource读取指定 properties 文件
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@PropertySource("classpath:website.properties")
@Getter
@Setter
class WebSite {
@Value("${url}")
private String url;
}
使用:
@Autowired
private WebSite webSite;
System.out.println(webSite.getUrl());//https://javaguide.cn/
5.题外话:Spring加载配置文件的优先级
Spring 读取配置文件也是有优先级的,直接上图:

本文源码:https://github.com/Snailclimb/springboot-guide/tree/master/source-code/basis/read-config-properties
Springboot优雅读配置文件的更多相关文章
- SpringBoot优雅的全局异常处理
前言 本篇文章主要介绍的是SpringBoot项目进行全局异常的处理. SpringBoot全局异常准备 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要求 JD ...
- Springboot 之 多配置文件
六.Springboot 之 多配置文件 说明:在程序开发过程中可能会有这样的需求:开发和部署的配置信息可能会不同,以传统的方式就是在配置文件里面写好配置,在部署的时候再去修改这些配置,这样肯定会 ...
- SpringBoot入坑-配置文件使用
经过上一篇的介绍,相信小伙伴们已经按奈不住内心对springboot的向往,本篇我将继续向小伙伴介绍springboot配置文件的配置,已经全局配置参数如何使用,好了下面开始我们今天的内容介绍. 我们 ...
- SpringBoot配置(1) 配置文件application&yml
SpringBoot配置(1) 配置文件application&yml 一.配置文件 1.1 配置文件 SpringBoot使用一个全局的配置文件,配置文件名是固定的. application ...
- SpringBoot注解把配置文件自动映射到属性和实体类实战
SpringBoot注解把配置文件自动映射到属性和实体类实战 简介:讲解使用@value注解配置文件自动映射到属性和实体类 1.配置文件加载 方式一 1.Controller上面配置 @Propert ...
- 六、Springboot 之 多配置文件
说明:在程序开发过程中可能会有这样的需求:开发和部署的配置信息可能会不同,以传统的方式就是在配置文件里面写好配置,在部署的时候再去修改这些配置,这样肯定会有很多问题,比如忘记修改.修改错误等. 而Sp ...
- jar包读取jar包内部和外部的配置文件,springboot读取外部配置文件的方法
jar包读取jar包内部和外部的配置文件,springboot读取外部配置文件的方法 用系统属性System.getProperty("user.dir")获得执行命令的目录(网上 ...
- 【springBoot】之配置文件application
springboot使用一个全局的配置文件application.properties或者是application.yml,放在在src/main/recesources下或者在类路径下的/confi ...
- springboot深入学习(一)-----springboot核心、配置文件加载、日志配置
一.@SpringBootApplication @SpringBootApplication是spring boot的核心注解,源码如下: 相当于:@Configuration+@EnableAut ...
- Springboot 之 自定义配置文件及读取配置文件
本文章来自[知识林] 读取核心配置文件 核心配置文件是指在resources根目录下的application.properties或application.yml配置文件,读取这两个配置文件的方法有两 ...
随机推荐
- python学习教材选哪个
python语言俨然成为当今最流行的国际语言,无论你是做AI的还是非AI,大家都在用python语言,各种平台也都开始支持python,现在连文科生都在学习python语言了,甚至很多表哥表姐的工作都 ...
- 人脸伪造图像检测:Deepfake魔高一尺,TextIn道高一丈
只因开了一个视频会议,直接被骗1.8个亿 今年2月,一家跨国公司的香港分公司财务人员被一场精心策划的Deepfake视频会议诈骗,导致公司损失2亿港币(约1.8亿人民币). 事件起因是财务人员收到 ...
- Spring —— bean实例化
bean 实例化 bean本质上就是对象,创建bean使用构造方法完成(反射) 构造方法(常用) 静态工厂* 实例工厂* FactoryBean(实 ...
- SVN(Linux)提交时强制写日志
SVN(Linux)提交时强制写日志 1.创建并修改pre-commit文件 进入svn/code/hooks目录,在svn版本库的hooks文件夹下面,复制模版pre-commit.tmplcp p ...
- 利用 ACME 实现SSL证书自动化配置更新
最近收到腾讯云的通知SSL证书要到期了,本想直接申请的发现现在申请的免费SSL证书有效期只有90天了,顺便了解了一下原因是包括Google在内的国际顶级科技公司一直都有在推进免费证书90天有效期的建议 ...
- Vue-Router 是干什么的,原理是什么?
传统的项目中,页面的切换和跳转使用的是超链接实现,但是目前的SPA 是基于组件和路由实现的,页面的切换和跳转是由路由机制完成,区别是更新了视图但不重新请求页面: 原理是把url 和组件之间建立映射关系 ...
- Spring 实现 3 种异步流式接口,干掉接口超时烦恼
大家好,我是小富- 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable.WebAsyncTask 和 DeferredResult.CompletableFuture等均可实现 ...
- .NET 7+Vue 3 开源仓库管理系统 ModernWMS
前言 本系统的设计目标是帮助中小企业乃至大型企业实现仓库操作的自动化与数字化,从而提升工作效率,降低成本,并最终实现业务增长.项目采用 Vue 3 + TS + .NET 7 等前沿框架进行开发,为企 ...
- 用JavaScriptt从一个路径字符串中获取文件名
思路 1.通过'\'关键字用split分割成数组 2.取分割后数组的最后一个就是文件名 3.另外,字符串中\是没意义的,需要2个\\ 相关代码 <script> var a='C:\\Pr ...
- 使用BackgroundService创建Windows 服务
使用管理员权限启动cmd.exe 安装服务 sc.exe create ".NET Joke Service" binpath="C:\Path\To\App.Windo ...