文章目录
- 前言
- 参考目录
- 实现步骤
- 1、包结构
- 2、Maven
- 3、自定义配置文件
- 4、application 文件
- 5、自定义数据库配置 `MyDataSource`
- 6、加密配置 `EncryptYamlProperties`
- 7、自定义读取yaml配置 `MyPropertySourceFactory`
- 8、测试加密解密
- 9、自定义 Properties 文件读取
- 10、测试自定义配置读取
 
- 最后说几句
 
前言
今天研究了一下关于配置文件的自定义加密,很久以前用过 jasypt 加密,依稀记得运行 jar 包的时候还得把密码写到执行命令里面,不大方便,然后碰巧看到有使用自定义 Yaml 文件的方式进行加密解密的,就试着玩了一下,这篇博客简单介绍一下用法,除了加密解密以外还有简单介绍一下配置文件的读取替换。
参考目录
- Using @PropertySource
- @PropertySource with YAML Files in Spring Boot
实现步骤
1、包结构

2、Maven
除了常见的配置以外,需要引入的是 Hutool 和 bcprov-jdk15to18,前者是加密工具类,后者是加密所需要的 jar。
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.8.16</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15to18</artifactId>
    <version>1.69</version>
</dependency>
除此之外,需要注意 <build> 标签下的配置,Maven 打包时会把 resources 文件夹下相应环境的文件替换到 properties 下。
<resource>
    <directory>${project.basedir}/src/main/resources/profile/${profiles.active}</directory>
    <filtering>true</filtering>
    <includes>
        <include>*.*</include>
    </includes>
    <targetPath>properties</targetPath>
</resource>
完整的代码可以看代码包。
3、自定义配置文件
以 dev 为例。
encrypt.yml
 
business.properties
 
4、application 文件
application.yml
 
application-dev.yml
 
5、自定义数据库配置 MyDataSource
 

 这里使用了工具类对配置文件的字符串解密之后再保存到 Hikari 配置中。
6、加密配置 EncryptYamlProperties
 

 @PropertySource 指定了引用的配置文件,以及读取配置的方法是 MyPropertySourceFactory,因为不能直接读取 Yaml 文件配置,所以需要转换成 Properties。
7、自定义读取yaml配置 MyPropertySourceFactory
 

8、测试加密解密
启动项目,如果正常启动就说明数据库连接正常,保险起见,引入了一个TestDemo 的类测试,也引入了 MyBatis-Plus 简化代码的书写。

请求成功:
 
9、自定义 Properties 文件读取
/**
 * 业务yaml文件配置
 *
 * @author Michelle.Chung
 */
@Component
public class BusinessProperties {
    /**
     * 文件路径
     */
    private static final String BUSINESS_PROPERTIES = "properties/business.properties";
    /**
     * 单例
     */
    private static final BusinessProperties INSTANCE = new BusinessProperties();
    private final Properties properties;
    public BusinessProperties() {
        try {
            this.properties = PropertiesLoaderUtils.loadAllProperties(BUSINESS_PROPERTIES);
        } catch (IOException e) {
            throw new RuntimeException("读取配置文件时出现异常...", e);
        }
    }
    /**
     * 获得当前实例
     *
     * @return
     */
    public static BusinessProperties getInstance() {
        return INSTANCE;
    }
    /**
     * 获取value值
     */
    public String getValue(String key) {
        if (null == properties || StrUtil.isBlank(key)) {
            return null;
        }
        return properties.getProperty(key);
    }
}
10、测试自定义配置读取

请求成功:

最后说几句
本文比较简单,我觉得这个功能用不用见仁见智吧,开始也只是看到觉得没有用过所以测试一下,也方便以后如果有机会的话可以参考。
(完)



















