Skip to content

项目配置说明

当你需要切换环境、排查“本地能跑线上不行”、或要把某个组件(Redis/MinIO/xxl-job 等)正确接入时,优先查这篇。

本文介绍 youlai-boot 的配置体系,你将了解:

  • 多环境配置与 profile 的使用方式
  • Spring Boot 配置加载优先级
  • 核心组件的常用配置项与注意事项

多环境配置

配置文件结构

src/main/resources/
├── application.yml            # 主配置文件(公共配置)
├── application-dev.yml        # 开发环境配置
├── application-prod.yml       # 生产环境配置
├── application-youlai.yml     # 演示环境配置
├── codegen.yml                # 代码生成器配置
└── logback-spring.xml         # 日志配置

配置文件加载优先级

Spring Boot 配置加载遵循 外层覆盖内层、特定覆盖通用 的原则:

优先级配置来源示例
1命令行参数--server.port=8080
2JVM 系统属性-Dserver.port=8080
3系统环境变量SERVER_PORT=8080
4application-{profile}.ymlapplication-prod.yml
5application.yml公共配置

激活环境配置

方式一:配置文件激活(推荐开发环境)

yaml
# application.yml
spring:
  profiles:
    active: dev # 激活开发环境

方式二:命令行激活(推荐生产环境)

bash
# Jar 包运行
java -jar youlai-boot.jar --spring.profiles.active=prod

# Docker 运行
docker run -e SPRING_PROFILES_ACTIVE=prod youlai-boot

方式三:环境变量激活

bash
# Linux/Mac
export SPRING_PROFILES_ACTIVE=prod

# Windows PowerShell
$env:SPRING_PROFILES_ACTIVE="prod"

配置覆盖策略

yaml
# application.yml(公共配置)
server:
  port: 8080

---
# application-dev.yml(开发环境)
server:
  port: 8000 # 覆盖公共配置

---
# application-prod.yml(生产环境)
server:
  port: 8989 # 覆盖公共配置
激活环境服务端口
dev8000
prod8989

敏感配置处理

推荐使用环境变量覆盖:

yaml
# application-prod.yml
spring:
  datasource:
    url: ${DB_URL:jdbc:mysql://localhost:3306/youlai_admin}
    username: ${DB_USERNAME:root}
    password: ${DB_PASSWORD:} # 必须通过环境变量设置

  data:
    redis:
      password: ${REDIS_PASSWORD:}

security:
  session:
    jwt:
      secret-key: ${JWT_SECRET_KEY:} # 必须通过环境变量设置

Docker Compose 环境变量配置:

yaml
environment:
  - DB_URL=jdbc:mysql://mysql:3306/youlai_admin
  - DB_USERNAME=youlai
  - DB_PASSWORD=your_secure_password
  - REDIS_PASSWORD=your_redis_password
  - JWT_SECRET_KEY=your_256_bit_secret_key_here

MySQL 配置

基础配置

yaml
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource # 连接池类型
    driver-class-name: com.mysql.cj.jdbc.Driver # 驱动类(可省略,SPI 自动发现)
    url: jdbc:mysql://localhost:3306/youlai_admin?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&autoReconnect=true&allowMultiQueries=true
    username: root
    password: your_password

JDBC URL 参数说明

参数说明推荐值
zeroDateTimeBehavior=convertToNull0000-00-00 日期转为 NULLconvertToNull
useUnicode=true使用 Unicode 编码true
characterEncoding=UTF-8字符编码UTF-8
serverTimezone=Asia/Shanghai服务器时区Asia/Shanghai
autoReconnect=true自动重连true
allowMultiQueries=true允许多语句true

Druid 连接池配置

yaml
spring:
  datasource:
    druid:
      initial-size: 5 # 初始连接数
      min-idle: 5 # 最小空闲连接数
      max-active: 20 # 最大连接数
      max-wait: 60000 # 获取连接最大等待时间(ms)
      time-between-eviction-runs-millis: 60000 # 检测间隔
      min-evictable-idle-time-millis: 300000 # 最小空闲时间
      validation-query: SELECT 1 # 验证 SQL
      test-while-idle: true # 空闲时检测
      test-on-borrow: false # 借出时检测
      test-on-return: false # 归还时检测

Redis 配置

基础配置

yaml
spring:
  data:
    redis:
      database: 0 # 数据库索引(0-15)
      host: localhost # Redis 服务器地址
      port: 6379 # 端口
      password: # 密码(无密码留空)
      timeout: 10s # 连接超时时间

连接池配置(Lettuce)

yaml
spring:
  data:
    redis:
      lettuce:
        pool:
          max-active: 8 # 最大连接数
          max-wait: -1 # 最大阻塞等待时间(-1 表示无限制)
          max-idle: 8 # 最大空闲连接
          min-idle: 0 # 最小空闲连接

缓存配置

yaml
spring:
  cache:
    type: redis # 缓存类型
    redis:
      time-to-live: 3600000 # 缓存过期时间(毫秒)
      cache-null-values: true # 缓存空值,防止缓存穿透

Redis 数据库规划

Database用途
0业务缓存
1Session 存储
2权限缓存
11开发环境

MinIO 对象存储配置

MinIO 配置

yaml
oss:
  type: minio # 存储类型
  minio:
    endpoint: http://localhost:9000 # 服务地址
    access-key: minioadmin # 访问密钥
    secret-key: minioadmin # 密钥
    bucket-name: public # 存储桶名称
    custom-domain: https://cdn.example.com # 自定义域名(可选)

阿里云 OSS 配置

yaml
oss:
  type: aliyun
  aliyun:
    endpoint: oss-cn-hangzhou.aliyuncs.com
    access-key-id: your-access-key-id
    access-key-secret: your-access-key-secret
    bucket-name: default

本地存储配置

yaml
oss:
  type: local
  local:
    # Mac: /Users/username/storage/
    # Windows: D:/storage/
    # Linux: /var/storage/
    storage-path: /var/storage/

安全认证配置

配置项概览

yaml
security:
  session:
    type: jwt # 会话类型 [jwt|redis-token]
    access-token-time-to-live: 7200 # 访问令牌有效期(秒)
    refresh-token-time-to-live: 604800 # 刷新令牌有效期(秒)
    jwt:
      secret-key: SecretKey012345678901234567890123456789012345678901234567890123456789
    redis-token:
      allow-multi-login: true # 是否允许多设备登录
  ignore-urls: # 白名单路径(仅跳过鉴权过滤器)
    - /api/v1/auth/login/**
    - /api/v1/auth/captcha
  unsecured-urls: # 非安全路径(完全绕过 Security)
    - /doc.html
    - /swagger-ui/**
    - /v3/api-docs/**

会话策略对比

策略特点适用场景
jwt无状态、服务端不存储令牌微服务、分布式系统
redis-token有状态、支持令牌主动失效单体应用、需要踢人下线

JWT 配置说明

yaml
security:
  session:
    type: jwt
    jwt:
      # HS256 算法要求密钥至少 32 字符
      # 生产环境必须使用环境变量覆盖
      secret-key: ${JWT_SECRET_KEY:SecretKey012345678901234567890123456789012345678901234567890123456789}

白名单路径说明

yaml
security:
  # 白名单路径:跳过 AuthorizationFilter,仍走其他 Security 过滤器
  ignore-urls:
    - /api/v1/auth/login/** # 登录接口
    - /api/v1/auth/captcha # 验证码

  # 非安全路径:完全绕过 Spring Security
  unsecured-urls:
    - /doc.html # Knife4j 文档
    - /swagger-ui/** # Swagger UI
    - /v3/api-docs/** # OpenAPI
配置项CORS/CSRF 过滤器认证过滤器鉴权过滤器
ignore-urls✅ 执行✅ 执行❌ 跳过
unsecured-urls❌ 跳过❌ 跳过❌ 跳过

MyBatis-Plus 配置

基础配置

yaml
mybatis-plus:
  mapper-locations: classpath*:/mapper/**/*.xml # Mapper XML 位置
  global-config:
    db-config:
      id-type: none # 主键类型(none=跟随数据库)
      logic-delete-field: isDeleted # 逻辑删除字段(实体属性名)
      logic-delete-value: 1 # 删除值
      logic-not-delete-value: 0 # 未删除值
  configuration:
    map-underscore-to-camel-case: true # 驼峰转换
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # SQL 日志

主键策略

策略说明适用数据库
none跟随数据库设置通用
auto数据库自增MySQL、PostgreSQL
assign_id雪花算法分布式系统
assign_uuidUUID无需排序的场景

其他配置

验证码配置

yaml
captcha:
  type: circle # 验证码类型 [circle|gif|line|shear]
  width: 120 # 宽度
  height: 40 # 高度
  interfere-count: 2 # 干扰元素数量
  text-alpha: 0.8 # 文本透明度
  code:
    type: math # 字符类型 [math|random]
    length: 1 # 算术位数或字符个数
  font:
    name: SansSerif # 字体名称
    weight: 1 # 样式(0=普通,1=粗体,2=斜体)
    size: 24 # 字体大小
  expire-seconds: 120 # 有效期(秒)

邮件配置

yaml
spring:
  mail:
    host: smtp.example.com # SMTP 服务器
    port: 587 # 端口
    username: your-email@example.com
    password: your-password
    properties:
      mail:
        smtp:
          auth: true # 启用认证
          starttls:
            enable: true # 启用 TLS
    from: noreply@example.com # 发件人地址

短信配置(阿里云)

yaml
sms:
  aliyun:
    accessKeyId: LTAI5tSMgfxxxxxxdiBJLyR
    accessKeySecret: SoOWRqpjtS7xxxxxxZ2PZiMTJOVC
    domain: dysmsapi.aliyuncs.com
    regionId: cn-shanghai
    signName: 系统名称
    templates:
      register: SMS_22xxx771 # 注册模板
      login: SMS_22xxx772 # 登录模板
      change-mobile: SMS_22xxx773 # 换绑手机模板

微信小程序配置

yaml
wx:
  miniapp:
    app-id: wx1234567890abcdef # 小程序 AppID
    app-secret: your-app-secret # 小程序 Secret

定时任务配置(XXL-JOB)

yaml
xxl:
  job:
    enabled: false # 是否启用
    admin:
      addresses: http://127.0.0.1:8686/xxl-job-admin
    accessToken: default_token
    executor:
      appname: xxl-job-executor-${spring.application.name}
      port: 9999
      logpath: /data/applogs/xxl-job/jobhandler
      logretentiondays: 30

接口文档配置

SpringDoc 配置:

yaml
springdoc:
  swagger-ui:
    path: /swagger-ui.html # Swagger UI 路径
    operationsSorter: alpha # 接口排序
    tags-sorter: alpha # 标签排序
  api-docs:
    path: /v3/api-docs # OpenAPI JSON 路径
  group-configs:
    - group: "系统管理"
      paths-to-match: "/**"
      packages-to-scan:
        - com.youlai.boot.auth.controller
        - com.youlai.boot.system.controller

Knife4j 配置:

yaml
knife4j:
  enable: true # 启用增强功能
  production: false # 生产环境保护(true=隐藏文档)
  setting:
    language: zh_cn # 语言

配置最佳实践

敏感信息管理

yaml
# ❌ 不推荐:硬编码敏感信息
spring:
  datasource:
    password: my_password_123

# ✅ 推荐:使用环境变量
spring:
  datasource:
    password: ${DB_PASSWORD:}

多环境配置策略

yaml
# application.yml(公共配置)
spring:
  application:
    name: youlai-boot
  servlet:
    multipart:
      max-file-size: 50MB

# application-dev.yml(开发环境)
server:
  port: 8000

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl  # 开启 SQL 日志

# application-prod.yml(生产环境)
server:
  port: 8989

mybatis-plus:
  configuration:
    log-impl:  # 关闭 SQL 日志

Docker Compose 配置示例

yaml
version: "3.8"
services:
  youlai-boot:
    image: youlai-boot:latest
    environment:
      - SPRING_PROFILES_ACTIVE=prod
      - DB_URL=jdbc:mysql://mysql:3306/youlai_admin
      - DB_USERNAME=youlai
      - DB_PASSWORD=your_secure_password
      - REDIS_HOST=redis
      - REDIS_PASSWORD=your_redis_password
      - JWT_SECRET_KEY=your_256_bit_secret_key
    ports:
      - "8989:8989"
    depends_on:
      - mysql
      - redis

配置文件索引

配置项配置文件位置属性类
安全配置security.*SecurityProperties.java
验证码配置captcha.*CaptchaProperties.java
邮件配置spring.mail.*MailProperties.java
短信配置sms.*AliyunSmsProperties.java
代码生成codegen.*CodegenProperties.java
对象存储oss.*OssProperties.java
定时任务xxl.job.*XxlJobProperties.java
接口文档springdoc.*SpringDocConfigProperties.java
Knife4jknife4j.*Knife4jProperties.java

下一步

基于 MIT 许可发布 · 由 ❤️ 和 ☕ 驱动 · 支持作者