当前位置: 首页 > news >正文

Java实现.env文件读取敏感数据

文章目录

    • 1.common-env-starter模块
        • 1.目录结构
        • 2.DotenvEnvironmentPostProcessor.java 在${xxx}解析之前执行,提前读取配置
        • 3.EnvProperties.java 这里的path只是为了代码提示
        • 4.EnvAutoConfiguration.java Env模块自动配置类
        • 5.spring.factories 自动配置和注册EnvironmentPostProcessor
        • 6.pom.xml
    • 2.common-env-starter-demo模块
        • 1.目录结构
        • 2.pom.xml
        • 3.application.yml 配置测试的数据
        • 4.EnvConfig.java
        • 5.EnvApplication.java 启动类
        • 6.测试

1.common-env-starter模块

1.目录结构

CleanShot 2025-01-10 at 20.38.24@2x

2.DotenvEnvironmentPostProcessor.java 在${xxx}解析之前执行,提前读取配置
package com.sunxiansheng.env.processor;import io.github.cdimascio.dotenv.Dotenv;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;/*** Description: 在${xxx}解析之前执行,可以读取xxx,设置到环境中,在后续的解析时就会进行替换了** @Author sun* @Create 2025/1/10 19:40* @Version 1.0*/
public class DotenvEnvironmentPostProcessor implements EnvironmentPostProcessor{@Overridepublic void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {// 从 Spring 的配置中获取 sun-rays.env.pathString dotenvPath = environment.getProperty("sun-rays.env.path");if (dotenvPath != null) {// 加载 .env 文件Dotenv dotenv = Dotenv.configure().directory(dotenvPath).filename(".env").load();// 将 .env 中的值注入到系统属性中,确保占位符解析时可用dotenv.entries().forEach(entry ->environment.getSystemProperties().put(entry.getKey(), entry.getValue()));System.out.println("Loaded .env from path: " + dotenvPath);} else {System.err.println("sun-rays.env.path not configured!");}}
}
3.EnvProperties.java 这里的path只是为了代码提示
package com.sunxiansheng.env.config.properties;import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;/*** Description: 这里的path只是为了代码提示,实际上DotenvEnvironmentPostProcessor.java不从这里获取配置** @Author sun* @Create 2025/1/10 20:04* @Version 1.0*/
@ConfigurationProperties(prefix = "sun-rays.env")
@Data
public class EnvProperties {/*** .env文件的绝对路径*/private String path;
}
4.EnvAutoConfiguration.java Env模块自动配置类
package com.sunxiansheng.env.config;import com.sunxiansheng.env.config.properties.EnvProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;/*** Description: Env模块自动配置类** @Author sun* @Create 2025/1/10 19:57* @Version 1.0*/
@Configuration
@EnableConfigurationProperties({EnvProperties.class}) // 启用配置类
@Slf4j
public class EnvAutoConfiguration {/*** 自动配置成功日志*/@PostConstructpublic void logConfigSuccess() {log.info("EnvAutoConfiguration has been loaded successfully!");}
}
5.spring.factories 自动配置和注册EnvironmentPostProcessor
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.sunxiansheng.env.config.EnvAutoConfiguration
org.springframework.boot.env.EnvironmentPostProcessor=\
com.sunxiansheng.env.processor.DotenvEnvironmentPostProcessor
6.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.sunxiansheng</groupId><artifactId>sunrays-common</artifactId><version>2.0.0</version></parent><artifactId>common-env-starter</artifactId><dependencies><!-- 可以使用.env文件提前加载配置,确保数据安全 --><dependency><groupId>io.github.cdimascio</groupId><artifactId>java-dotenv</artifactId></dependency></dependencies>
</project>

2.common-env-starter-demo模块

1.目录结构

CleanShot 2025-01-10 at 21.03.43@2x

2.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.sunxiansheng</groupId><artifactId>sunrays-common-demo</artifactId><version>2.0.0</version></parent><artifactId>common-env-starter-demo</artifactId><dependencies><!-- common-env-starter --><dependency><groupId>com.sunxiansheng</groupId><artifactId>common-env-starter</artifactId><version>2.0.0</version></dependency></dependencies>
</project>
3.application.yml 配置测试的数据
sun-rays:log4j2:home: /Users/sunxiansheng/IdeaProjects/sunrays-framework/sunrays-common-demo/common-env-starter-demo/logs # 日志根目录(默认./logs)module: sunrays-common-demo/common-env-starter-demo # 模块根目录从仓库根目录开始(默认defaultModule)env:path: /Users/sunxiansheng/IdeaProjects/sunrays-framework/sunrays-common-demo/common-env-starter-demo # .env文件的绝对路径
env:test: ${ENV_TEST}
4.EnvConfig.java
package com.sunxiansheng.env.config;import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;import javax.annotation.PostConstruct;/*** Description: Env配置类,测试读取数据** @Author sun* @Create 2025/1/10 20:55* @Version 1.0*/
@Configuration
@Slf4j
public class EnvConfig {@Value("${env.test}")private String test;@PostConstructpublic void init() {// 测试读取log.info("test={}", test);}
}
5.EnvApplication.java 启动类
package com.sunxiansheng.env;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;/*** Description: Env** @Author sun* @Create 2025/1/10 20:53* @Version 1.0*/
@SpringBootApplication
public class EnvApplication {public static void main(String[] args) {SpringApplication.run(EnvApplication.class, args);}
}
6.测试

CleanShot 2025-01-10 at 21.07.43@2x

CleanShot 2025-01-10 at 21.07.53@2x

http://www.lryc.cn/news/529295.html

相关文章:

  • Go反射指南
  • Fullcalendar @fullcalendar/react 样式错乱丢失问题和导致页面卡顿崩溃问题
  • 【电工基础】4.低压电器元件,漏电保护器,熔断器,中间继电器
  • 有限元分析学习——Anasys Workbanch第一阶段笔记梳理
  • C++中常用的十大排序方法之1——冒泡排序
  • vscode+WSL2(ubuntu22.04)+pytorch+conda+cuda+cudnn安装系列
  • 手撕Diffusion系列 - 第十一期 - lora微调 - 基于Stable Diffusion(代码)
  • 【Block总结】OutlookAttention注意力,捕捉细节和局部特征|即插即用
  • 网络攻防实战指北专栏讲解大纲与网络安全法
  • 【已解决】windows7虚拟机安装VMtools频繁报错
  • 蓝桥杯模拟算法:多项式输出
  • 冲刺蓝桥杯之速通vector!!!!!
  • 知识管理平台在数字经济时代推动企业智慧决策与知识赋能的路径分析
  • IT服务管理平台(ITSM):构建高效运维体系的基石
  • [EAI-026] DeepSeek-VL2 技术报告解读
  • 深度学习:基于MindNLP的RAG应用开发
  • 【C语言】static关键字的三种用法
  • STM32 PWMI模式测频率占空比
  • 神经网络|(四)概率论基础知识-古典概型
  • ubuntu20.04.6下运行VLC-Qt例子simple-player
  • 低代码产品插件功能一览
  • Blazor-@bind
  • RK3568中使用QT opencv(显示基础图像)
  • [答疑]DDD伪创新哪有资格和仿制药比
  • C#,入门教程(05)——Visual Studio 2022源程序(源代码)自动排版的功能动画图示
  • DIY QMK量子键盘
  • C++ 堆栈分配的区别
  • 范冰冰担任第75届柏林电影节主竞赛单元评委 共鉴电影佳作
  • Pandas进行MongoDB数据库CRUD
  • 《DeepSeek 实用集成:大模型能力接入各类软件》