配置管理¶
数据库账号、端口号、JWT 密钥这些"会变的东西",不能硬编码在 Java 里,要放配置文件。
application.yml¶
Spring Boot 默认读 src/main/resources/application.yml(或 .properties)。本书 task-manager 的配置:
# 任务管理系统 · Spring Boot 配置
server:
port: 8080
spring:
application:
name: task-manager
# 数据源:跑起来需本地 MySQL,先建库 task_manager(建表 SQL 见 docs 第 27 章)
datasource:
url: jdbc:mysql://localhost:3306/task_manager?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
username: root
password: your_password
driver-class-name: com.mysql.cj.jdbc.Driver
# MyBatis-Plus 配置(第 26 章)
mybatis-plus:
configuration:
map-underscore-to-camel-case: true # user_name 自动映射到 userName
global-config:
db-config:
logic-delete-field: deleted # 逻辑删除字段
logic-delete-value: 1
logic-not-delete-value: 0
# JWT 配置(第 29 章)
jwt:
# HS256 要求密钥至少 32 字节。生产环境务必换成随机长密钥并放环境变量,别硬编码!
secret: javaglm-task-manager-jwt-secret-key-change-me-please-32bytes
expire-millis: 86400000 # 24 小时
logging:
level:
com.javaglm: debug
对标前端:像 .env 文件 + Vite 的 import.meta.env。YAML 用缩进表示层级,比 properties 直观。
读配置:@Value¶
Java 代码里用 @Value("${键名}") 注入配置值。JwtUtil 读 JWT 密钥和过期时间就是这么干的:
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expire-millis:86400000}") // 冒号后是默认值
private long expireMillis;
完整代码:
package com.javaglm.task.security;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
/**
* JWT 工具类(第 29 章)。
* 对标前端:后端签发 token,前端存在 localStorage,每次请求带在 Authorization 头里。
* 这里负责"签发"和"解析校验"。
*/
@Component
public class JwtUtil {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expire-millis:86400000}")
private long expireMillis; // 默认 24 小时
private SecretKey key() {
// HS256 要求密钥至少 32 字节
return Keys.hmacShaKeyFor(secret.getBytes(StandardCharsets.UTF_8));
}
/** 签发 token:把 userId 放进 subject,username 放进自定义 claim。 */
public String generateToken(Long userId, String username) {
Date now = new Date();
Date expiry = new Date(now.getTime() + expireMillis);
return Jwts.builder()
.setSubject(String.valueOf(userId))
.claim("username", username)
.setIssuedAt(now)
.setExpiration(expiry)
.signWith(key(), SignatureAlgorithm.HS256)
.compact();
}
/** 解析 token,签名错误或过期会抛异常(由拦截器捕获转 401)。 */
public Claims parseToken(String token) {
return Jwts.parserBuilder()
.setSigningKey(key())
.build()
.parseClaimsJws(token)
.getBody();
}
public Long getUserId(String token) {
return Long.valueOf(parseToken(token).getSubject());
}
}
多环境:profiles¶
开发/测试/生产用不同配置(开发连本地库,生产连线上库)。拆成多个文件:
application.yml—— 公共配置application-dev.yml—— 开发环境application-prod.yml—— 生产环境
激活某个环境:
或启动时指定:java -jar app.jar --spring.profiles.active=prod。
敏感配置别提交
数据库密码、JWT 密钥这类敏感信息,生产环境用环境变量注入,不要明文写进 yml 提交到 git。
@Value("${DB_PASSWORD}") 会自动读同名环境变量。
常用配置项速查¶
| 配置 | 作用 |
|---|---|
server.port |
服务端口 |
spring.datasource.* |
数据库连接 |
spring.profiles.active |
当前环境 |
logging.level.* |
日志级别 |
mybatis-plus.* |
MyBatis-Plus 配置 |
:octicons-arrow-left-16: 上一章:统一响应与全局异常 | 下一章:MyBatis-Plus 数据访问