SpringBoot系列——加载自定义配置文件
前言
SpringBoot启动时默认加载bootstrap.properties或bootstrap.yml(这两个优先级最高)、application.properties或application.yml,如果我们配置了spring.profiles,同时会加载对应的application-{profile}.properties或application-{profile}.yml,profile为对应的环境变量,比如dev,如果没有配置,则会加载profile=default的配置文件
虽然说配置项都写在同一个配置文件没有问题,但我们仍然希望能分开写,这样比较清晰,比如eureka的配置写在eureka.properties,数据库相关的配置写在datasource.properties等等,因此就需要设置加载外部配置文件
更多关于配置项信息请看官网:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#boot-features-external-config
本文记录SpringBoot加载自定义配置文件的两个方法
两种方法
方法一
直接在具体的类上面使用注解加载
比如当你在ServiceAImpl需要使用到xxx.properties时
//手动加载自定义配置文件
@PropertySource(value = {
"classpath:xxx.properties",
}, encoding = "utf-8")
@Service
public class ServiceAImpl{ @Value("${cn.huanzi.qch.xxx}")
private String xxx; }
如果你需要在更早一点引入,则可以在启动类上进行引入
//手动加载自定义配置文件
@PropertySource(value = {
"classpath:xxx.properties",
"classpath:yyy.properties",
"classpath:zzz.yml",
}, encoding = "utf-8") @Component
@SpringBootApplication
public class SpringbootLoadmyprofilesApplication { public static void main(String[] args) {
SpringApplication.run(SpringbootLoadmyprofilesApplication.class, args);
} @Value("${cn.huanzi.qch.xxx}")
private String xxx; @Value("${cn.huanzi.qch.yyy}")
private String yyy; @Value("${cn.huanzi.qch.zzz}")
private String zzz; @Bean
void index(){
System.out.println(xxx);
System.out.println(yyy);
System.out.println(zzz);
}
}
如果我们只是在业务中需要用到自定义配置文件的值,这样引入并没有什么问题,但外部配置是一些启动项,SpringBoot官网并不推荐我们这样干

虽然在@SpringBootApplication上使用@PropertySource似乎是在环境中加载自定义资源的一种方便而简单的方法,但我们不推荐使用它,因为SpringBoot在刷新应用程序上下文之前就准备好了环境。使用@PropertySource定义的任何键都加载得太晚,无法对自动配置产生任何影响。
这种情况下需要采用第二种方法
方法二
自定义环境处理类,在启动之前定制环境或应用程序上下文,
Customize the Environment or ApplicationContext Before It Starts:https://docs.spring.io/spring-boot/docs/2.1.0.RELEASE/reference/htmlsingle/#howto-customize-the-environment-or-application-context

官网还提供了一个列子:

我们也来写一个自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
package cn.huanzi.qch.springbootloadmyprofiles; import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource; import java.io.IOException;
import java.util.Properties; /**
自定义环境处理,在运行SpringApplication之前加载任意配置文件到Environment环境中
*/
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor { //Properties对象
private final Properties properties = new Properties(); @Override
public void postProcessEnvironment(ConfigurableEnvironment environment,SpringApplication application) {
//自定义配置文件
String[] profiles = {
"xxx.properties",
"yyy.properties",
"zzz.yml",
}; //循环添加
for (String profile : profiles) {
//从classpath路径下面查找文件
Resource resource = new ClassPathResource(profile);
//加载成PropertySource对象,并添加到Environment环境中
environment.getPropertySources().addLast(loadProfiles(resource));
}
} //加载单个配置文件
private PropertySource<?> loadProfiles(Resource resource) {
if (!resource.exists()) {
throw new IllegalArgumentException("资源" + resource + "不存在");
}
try {
//从输入流中加载一个Properties对象
properties.load(resource.getInputStream());
return new PropertiesPropertySource(resource.getFilename(), properties);
}catch (IOException ex) {
throw new IllegalStateException("加载配置文件失败" + resource, ex);
}
}
}
并且在META-INF/spring.factories中
#启用我们的自定义环境处理类
org.springframework.boot.env.EnvironmentPostProcessor=cn.huanzi.qch.springbootloadmyprofiles.MyEnvironmentPostProcessor
简单测试
先看一下我们的工程结构

xxx、yyy、zzz里面就只有一个值(yyy、zzz就对应改成yyy、zzz)
cn.huanzi.qch.xxx=this is xxx
如果不手动加载自定义配置文件,启动将会报错

因为我们这里不是启动项,方法一、方法二启动效果都差不多

后记
部分代码参考:https://www.jianshu.com/p/7ab1a62b04ed?from=timeline
代码开源
代码已经开源、托管到我的GitHub、码云:
GitHub:https://github.com/huanzi-qch/springBoot
码云:https://gitee.com/huanzi-qch/springBoot
SpringBoot系列——加载自定义配置文件的更多相关文章
- SpringBoot之加载自定义配置文件
SpringBoot默认加载配置文件名为:application.properties和application.yml,如果需要使用自定义的配置文件,则通过@PropertySource注解指定. J ...
- SpringBoot启动加载yml配置文件出现编码格式错误
Caused by: org.yaml.snakeyaml.error.YAMLException: java.nio.charset.MalformedInputException: Input l ...
- spring-boot 如何加载rsources下面的自定义配置文件
spring-boot 如何加载resources下面的自定义配置文件 https://segmentfault.com/q/1010000006828771?_ea=1144561
- springboot加载外部配置文件
网上搜集和整理如下(自己已验证过) 1. war包在tomcat中加载外部配置文件 war包运行在独立tomcat下时,如何加载war包外部配置application.properties,以达到每次 ...
- SpringBoot加载子模块配置文件的方法
这两天开始学习SpringBoot框架,按照官方的文档,很轻易地就把单模块的项目启动了,但在使用maven搭建多模块的时候遇到了子模块配置文件没有加载的问题 项目架构是这样的 zero |-ws |- ...
- Springboot默认加载application.yml原理以及扩展
Springboot默认加载application.yml原理以及扩展 SpringApplication.run(...)默认会加载classpath下的application.yml或applic ...
- [Yii2.0] 以Yii 2.0风格加载自定义类或命名空间 [配置使用Yii2 autoloader]
Yii 2.0最显著的特征之一就是引入了命名空间,因此对于自定义类的引入方式也同之前有所不同.这篇文章讨论一下如何利用Yii 2.0的自动加载机制,向系统中引入自定义类和命名空间.本文旨在抛砖引玉,如 ...
- selenium启动Chrome时,加载用户配置文件
selenium启动Chrome时,加载用户配置文件 Selenium操作浏览器是不加载任何配置的,网上找了半天,关于Firefox加载配置的多点,Chrome资料很少,下面是关于加载Chrome ...
- 基于.net 的加载自定义配置-误操作
有时候 需要 将程序加载自定义的配置文件,除了自己写解析xml文件.内置的ConfigutionManager对象 是个不错的选项. 按照 app.config 的方式,做一个副本.然后从你的配置文件 ...
随机推荐
- std::string 简单入门
string的定义原型 typedef basic_string<char, char_traits<char>, allocator<char> > string ...
- 面向对象举例(一) —— 顶点(vertex)、边(edge)与图(graph)
Graph: class Graph(dict): def __init__(self, vs=[], es=[]): for v in vs: self.add_vertex(v) for e in ...
- Android sendToTarget
在使用message进行handler的数据交互的时候不可避免的会使用到message作为数据的载体,可是在使用message的时候有人会直接new一个message,有人会使用handler.obt ...
- Select2使用方法汇总
引用: <script src="~/Content/plugins/select2/select2.min.js"></script> 1.简单使用 $. ...
- ios技术支持网址
如有任何问题可以留言: 邮箱地址:cccliche@outlook.com
- [LeetCode OJ] Copy List with Random Pointer 扩大
职务地址:https://oj.leetcode.com/problems/copy-list-with-random-pointer/ 题意:对一个有回路的链表的深复制 解题:这道题我AC了之后才发 ...
- go与java互用的AES实现
终于实现了go与java互用的AES算法实现.基于go可以编译windows与linux下的命令行工具,十分方便. Java源码 import java.security.GeneralSecurit ...
- v-charts显示标题
使用v-charts的时候,如果要显示标题需要以下操作 1. 加入:title props <ve-pie :title="chartTitle" :data="c ...
- 基于Spring开发
1. XML Schema 1.1 最简单的标签 一个最简单的标签,形式如: <bf:head-routing key="1" value="1" to= ...
- Android零基础入门第26节:layout_gravity和gravity大不同
原文:Android零基础入门第26节:layout_gravity和gravity大不同 上一期我们一起学习了LinearLayout线性布局的方向.填充模型和权重,本期来一起学习LinearLay ...