如何在Spring Boot应用中配置STRIPE_SECRET_KEY?
问题
项目包含ChargeRequest、PaymentStatus实体类,以及StripeService、ChargeController、CheckoutController控制器。已在.bashrc中配置环境变量:
STRIPE_SECRET_KEY=my_key
但启动时抛出异常:
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'STRIPE_SECRET_KEY' in value "${STRIPE_SECRET_KEY}"
StripeService代码如下:
package com.edoyou.k2sbeauty.services.implementations; import com.edoyou.k2sbeauty.entities.model.ChargeRequest; import com.stripe.Stripe; import com.stripe.exception.APIConnectionException; import com.stripe.exception.APIException; import com.stripe.exception.CardException; import com.stripe.exception.InvalidRequestException; import com.stripe.model.Charge; import jakarta.annotation.PostConstruct; import java.util.HashMap; import java.util.Map; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Service; @Service public class StripeService { @Value("${STRIPE_SECRET_KEY}") private String secretKey; @PostConstruct public void init() { Stripe.apiKey = secretKey; } public Charge charge(ChargeRequest chargeRequest) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException, com.stripe.exception.AuthenticationException { Map<String, Object> chargeParams = new HashMap<>(); chargeParams.put("amount", chargeRequest.getAmount()); chargeParams.put("currency", chargeRequest.getCurrency()); chargeParams.put("description", chargeRequest.getDescription()); chargeParams.put("source", chargeRequest.getStripeToken()); return Charge.create(chargeParams); } }
解决方法
1. 确认环境变量已生效
修改.bashrc后,必须重新加载配置或重启终端,否则新变量不会被当前会话读取:
source ~/.bashrc
执行以下命令验证变量是否存在:
echo $STRIPE_SECRET_KEY
若输出my_key,说明变量已成功加载。
2. 确保IDE拾取环境变量
如果是在IDE中运行项目,IDE可能不会自动读取终端的环境变量。以IntelliJ IDEA为例:
- 打开「Run/Debug Configurations」
- 选择你的应用配置
- 在「Environment variables」中手动添加
STRIPE_SECRET_KEY=my_key - 保存后重新启动应用
3. 配置文件兜底方案
如果环境变量方式仍不生效,可以在application.properties中添加配置:
# 优先读取环境变量,不存在则使用默认值(可选) STRIPE_SECRET_KEY=${STRIPE_SECRET_KEY:your_default_key}
注意:生产环境不建议直接硬写密钥,仅用于本地调试。
4. 检查Spring配置
Spring默认会自动读取系统环境变量,无需额外配置。如果使用了@PropertySource注解,确保没有限制环境变量的读取。
内容的提问来源于stack exchange,提问作者EDOYou
相关产品推荐
相关产品推荐

