springboot配置文件外置处理
前言:
在springboot项目中,一般的配置文件都在resource/config下面,它可以以两种方式存在,一种是yml,一种是properties方式。
当运维和开发分开的时候,比如连接mysql数据库生产上的时候,运维不会告诉你账户和密码,需要将配置文件放到固定的目录下,运维自己去配置。这样就需要配置文件外置。
当配置文件外置的时候,他是在项目启动的时候,自己去加载配置文件。下面请看实现。
1. 需要增加一个文件
spring.factories,这个文件里面配置启动的时候需要初始化的信息
org.springframework.boot.env.EnvironmentPostProcessor=cn.fintecher.pangolin.service.common.config.AutoConfigEnvironmentPostProcessor
2. 在AutoConfigEnvironmentPostProcessor这个类中增加如下代码
package cn.fintecher.pangolin.service.common.config; import cn.fintecher.pangolin.common.utils.AutoConfigEnvironmentUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertySourceLoader;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.SpringFactoriesLoader; import java.util.List; @Order(1)
public class AutoConfigEnvironmentPostProcessor implements EnvironmentPostProcessor { private final Logger logger = LoggerFactory.getLogger(AutoConfigEnvironmentPostProcessor.class); private final ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); private final List<PropertySourceLoader> propertySourceLoaders; public AutoConfigEnvironmentPostProcessor() {
super();
this.propertySourceLoaders = SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader());
} @Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
AutoConfigEnvironmentUtil.postProcessEnvironment(environment, application, propertySourceLoaders, resourcePatternResolver, logger);
} } 公共方法:
public static void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application,
List<PropertySourceLoader> propertySourceLoaders, ResourcePatternResolver resourcePatternResolver,
Logger logger) { String[] activeProfiles = environment.getActiveProfiles();
for (String activeProfile : activeProfiles) {
if (Objects.equals(activeProfile, "swagger"))
continue;
for (PropertySourceLoader loader : propertySourceLoaders) {
for (String fileExtension : loader.getFileExtensions()) {
if (!fileExtension.equals("yml"))
continue; String applicationLocal = ResourceUtils.CLASSPATH_URL_PREFIX + "/config/application.yml";
try {
Resource applicationResource = resourcePatternResolver.getResource(applicationLocal);
List<PropertySource<?>> applactionYML = loader.load(ResourceUtils.CLASSPATH_URL_PREFIX + "/config/application.yml", applicationResource);
applactionYML.stream().forEach(environment.getPropertySources()::addLast); } catch (IOException e) {
e.printStackTrace();
} String path = (String) environment.getPropertySources().get("applicationConfig: [classpath:/config/application.yml]").getProperty("spring.config.location"); String location = path + "/application-" + activeProfile + "." + fileExtension;
try {
Resource[] resources = resourcePatternResolver.getResources(location);
for (Resource resource : resources) {
List<PropertySource<?>> propertySources = loader.load(resource.getFilename(), resource);
if (null != propertySources && !propertySources.isEmpty()) {
propertySources.stream().forEach(environment.getPropertySources()::addLast);
}
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}
}
}
3. 在代码中获取了spring.config.location这个配置文件,这个配置文件在application.yml中配置如下
spring:
application:
name: common-service
config:
location: @profile.properties@
@profile.properties@ 取的是pom文件中的
<profile.properties>file:d:/tomcat/profiles/${project.artifactId}/properties</profile.properties>
这样这个配置文件就可以放在任何目录下面。
4. 其他信息比如logger日志也需要放在外面,在application.yml增加如下配置即可。
ps: 不需要改动的配置信息都可以配置在application.yml中。
logging:
config: @profile.properties@/logback-spring.xml
5. 可以试试。
springboot配置文件外置处理的更多相关文章
- SpringBoot使用外置的Servlet容器
SpringBoot默认使用嵌入式的Servlet容器,应用打包成可执行的jar包 优点:简单.便携 缺点:默认不支持jsp,优化定制比较复杂(使用定制器serverProperties.自定义Emb ...
- 解决spring-boot配置文件使用加密方式保存敏感数据启动报错No decryption for FailsafeTextEncryptor. Did you configure the keystore correctly
spring-boot配置文件使用加密方式保存敏感数据 application.yml spring: datasource: username: dbuser password: '{cipher} ...
- springboot配置文件中使用当前配置的变量
在开发中,有时我们的application.properties某些值需要重复使用,比如配置redis和数据库或者mongodb连接地址,日志,文件上传地址等,且这些地址如果都是相同或者父路径是相同的 ...
- SpringBoot 配置文件存放位置及读取顺序
SpringBoot配置文件可以使用yml格式和properties格式 分别的默认命名为:application.yml.application.properties 存放目录 SpringBoot ...
- [SpringBoot] - 配置文件的多种形式及JSR303数据校验
Springboot配置文件: application.yml application.properties(自带) yml的格式写起来稍微舒服一点 在application.properties ...
- 将springboot配置文件中的值注入到静态变量
SpringBoot配置文件分为.properties和.yml两种格式,根据启动环境的不同获取不同环境的的值. spring中不支持直接注入静态变量值,利用spring的set注入方法注入静态变量 ...
- SpringBoot配置文件 application.properties详解
SpringBoot配置文件 application.properties详解 本文转载:https://www.cnblogs.com/louby/p/8565027.html 阅读过程中若发现 ...
- Spring-Boot配置文件数据源配置项
Spring-Boot配置文件数据源配置项(常用配置项为红色) 参数 介绍 spring.datasource.continue-on-error = false 初始化数据库时发生错误时,请勿停止 ...
- 【日常错误】spring-boot配置文件读取不到
最近在用spring-boot做项目时,遇到自定义的配置文件无法读取到的问题,通过在appcation.java类上定义@PropertySource(value = {"classpath ...
随机推荐
- JDK源码阅读—ArrayList的实现
1 继承结构图 ArrayList继承AbstractList,实现了List接口 2 构造函数 transient Object[] elementData; // 数组保存元素 private i ...
- jquery 显示和隐藏的三种方式
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> & ...
- centos搭建免费的ssl证书,大部分浏览器均支持!(let’s encrypt 的使用记录)
安装certbot wget https://dl.eff.org/certbot-auto chmod a+x certbot-auto 然后就是通过这个脚本获取证书,安装前先将NGINX 停一下. ...
- WPF常用第三方控件
NLog日志控件: Install-Package NLog.Config Mysql数据库控件: Install-Package Mysql.Data 最新版本只支持.net 4.5.2及以上版本, ...
- 毕设(二)C#SerialPort
毕业设计中,用到串口与无人机通信,所以就用到了SerialPort这个类,这个类在设置属性时, 用到最主要的属性应该是COM口和波特率,由于本人不熟悉硬件,不便多说,但经验告诉我是这样的, 还有数据位 ...
- Delphi 导出数据至Excel的7种方法
一; delphi 快速导出excel uses ComObj,clipbrd; function ToExcel(sfilename:string; ADOQuery:TADOQuery):bool ...
- C#实现bitmap图像矫正
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- QT 强制杀死进程
bool KillProcess(QString ProcessName){ bool result = false; QString str1; HANDLE hSnapShot = Create ...
- Codility---CountFactors
Task description A positive integer D is a factor of a positive integer N if there exists an integer ...
- Java基础(五) final关键字浅析
前面在讲解String时提到了final关键字,本文将对final关键字进行解析. static和final是两个我们必须掌握的关键字.不同于其他关键字,他们都有多种用法,而且在一定环境下使用,可以提 ...