如何在 Spring Boot 中安全读取账号密码等

在开发 Spring Boot 项目时,经常需要实现发送邮件的功能,例如用户注册的邮箱验证码、忘记密码邮件等。通常,邮箱账号和密码会写在配置文件 application.yml 中,但这样做存在安全隐患:

  • 敏感信息暴露:一旦提交到 Git 仓库,邮箱账号和密码就可能被泄露。
  • 多环境不灵活:开发、测试、生产环境可能使用不同邮箱,如果写死在配置文件里,每次都需要修改。

为了解决这个问题,我们可以将 邮箱账号和密码存放到环境变量 中,让 Spring Boot 从环境变量安全读取。下面详细说明操作步骤。


1️⃣ 在电脑/服务器上设置环境变量

Windows PowerShell

powershell 复制代码
setx MAIL_USERNAME "0811500009@163.com"
setx MAIL_PASSWORD "eagfsdcJssgXsa"

Linux / macOS

bash 复制代码
export MAIL_USERNAME="0811500009@163.com"
export MAIL_PASSWORD="eagfsdcJssgXsa"

⚠️ 设置好后,最好重新启动 IDE 或终端,让环境变量生效。


2️⃣ 修改 application.yml 使用占位符

在配置文件中使用 ${环境变量名} 形式占位,Spring Boot 会自动读取:

yaml 复制代码
mail:
  host: smtp.163.com
  username: ${MAIL_USERNAME}   # 从环境变量读取
  password: ${MAIL_PASSWORD}   # 从环境变量读取
  code:
    overtime: 5

这样就不用在配置文件里暴露邮箱账号和密码。


3️⃣ Java 代码里使用

通过 @ConfigurationProperties 注入配置:

java 复制代码
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "mail")
public class MailCodeConfig {
    private String host;
    private String username;
    private String password;
    private Code code;

    public static class Code {
        private int overtime;

        // getter / setter
    }

    // getter / setter
}

然后在代码里直接使用:

java 复制代码
String username = mailCodeConfig.getUsername();
String password = mailCodeConfig.getPassword();
相关推荐
码途行者3 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员3 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇5 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu6 小时前
python:DecisionTree
开发语言·后端·python·算法
Cosolar6 小时前
从 Java 21 升到 25、Spring Boot 3 升 4:一次可复现的迁移踩坑实录
java·后端·面试
ShineWinsu6 小时前
对于Qt:事件的解析
c++·qt·面试·笔试·gui·客户端·事件
geovindu7 小时前
python: Decision Tree Regressor
开发语言·后端·python·算法·决策树
码事漫谈7 小时前
黄仁勋的来时路
后端
Joy T7 小时前
Spring Security 从 Acegi 到 AI Agent——JWT、角色鉴权与异步任务安全实战
人工智能·安全·spring·spring security·json web token·securitycontext·多次鉴权
IT空门:门主8 小时前
LangChain4j 1.24.0 深度解读:新特性、版本对比与学习路线
java·学习