Spring Boot 与 Spring Cloud 应用配置文件分类详解

基于Spring Boot和Spring Cloud实现微服务架构学习(四)-Spring Cloud总结 基于Spring Boot和Spring Cloud框架开发的微服务架构学习(四)-Spring Cloud总结 Spring Cloud包含了多个子项目(针对分布式系统中涉及的多个不同开源产品),之前在第一章节也介绍这些,比如:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring Cloud Commons、Spring Cloud Z 阅读详情

1. 配置文件分类

1.1 Spring Boot 配置文件分类

1.1.1 按环境分类
  • application.yml:主配置文件,适用于所有环境
  • application-{profile}.yml:环境特定配置文件
    • application-dev.yml:开发环境
    • application-test.yml:测试环境
    • application-staging.yml:预发布环境
    • application-prod.yml:生产环境
1.1.2 按位置分类(加载优先级从高到低)
  1. 命令行参数
  2. java:comp/env 中的 JNDI 属性
  3. Java 系统属性 (System.getProperties())
  4. 操作系统环境变量
  5. jar 包外部的 application-{profile}.properties/yml
  6. jar 包内部的 application-{profile}.properties/yml
  7. jar 包外部的 application.properties/yml
  8. jar 包内部的 application.properties/yml

1.2 Spring Cloud 配置文件分类

1.2.1 客户端配置文件
  • bootstrap.yml:引导配置文件(Spring Boot 2.4+ 需要额外依赖)
  • application.yml:应用配置文件
1.2.2 配置中心配置文件
  • {application-name}-{profile}.yml:存储在配置中心的配置文件

2. 配置加载机制详解

2.1 Spring Boot 配置加载顺序(优先级从高到低)

1. 命令行参数 (--server.port=8081)
2. SPRING_APPLICATION_JSON 中的属性
3. ServletConfig 初始化参数
4. ServletContext 初始化参数
5. JNDI 属性
6. Java 系统属性 (System.getProperties())
7. 操作系统环境变量
8. RandomValuePropertySource 配置的 random.* 属性
9. jar 包外部的 profile-specific 配置文件
10. jar 包内部的 profile-specific 配置文件
11. jar 包外部的 application 配置文件
12. jar 包内部的 application 配置文件
13. @Configuration 类上的 @PropertySource 注解
14. 默认属性 (SpringApplication.setDefaultProperties)

2.2 Spring Cloud 配置加载机制

2.2.1 核心概念:加载顺序 vs 优先级顺序

重要澄清:加载顺序 ≠ 优先级顺序

  • 加载顺序:指配置文件被读取的时间先后
  • 优先级顺序:指同名属性最终生效的规则
2.2.2 实际优先级顺序(从高到低)
1. 命令行参数
2. 环境变量
3. 配置中心配置(user-service.yml, user-service-dev.yml)← 高优先级
4. 本地 application-{profile}.yml
5. 本地 application.yml
6. bootstrap.yml (Spring Boot 2.4+ 不推荐使用)
7. 默认属性
2.2.3 关键结论
  • 配置中心配置优先级高于本地 application 配置
  • 相同属性名时,配置中心的值会覆盖本地配置
  • 这是 Spring Cloud Config 的核心设计理念

2.3 Spring Boot 2.4+ 的重大变化

2.3.1 bootstrap.yml 默认行为变化

Spring Boot 2.3 及之前版本:

  • bootstrap.yml 默认会被自动加载
  • 无需额外依赖

Spring Boot 2.4 及之后版本:

  • bootstrap.yml 默认被禁用,不会被加载
  • 必须显式引入 spring-cloud-starter-bootstrap 依赖才能启用
2.3.2 官方推荐的新配置方式

Spring Boot 2.4+ 推荐使用 spring.config.import 方式:

# application.yml(新方式)
spring:
  application:
    name: user-service
  config:
    import: 
      - optional:configserver:http://config-server:8888

3. 详细配置文件示例

3.1 bootstrap.yml 示例(Spring Cloud 引导配置)

# bootstrap.yml - Spring Cloud 引导配置文件
# 说明:此文件在 application.yml 之前加载,主要用于配置配置中心连接信息
# 注意:Spring Boot 2.4+ 需要 spring-cloud-starter-bootstrap 依赖

# 应用基本信息配置
spring:
  # 应用名称,也是配置中心中配置文件的前缀名
  application:
    name: user-service
  
  # 配置中心相关配置
  cloud:
    # 配置中心客户端配置
    config:
      # 配置中心服务器地址
      uri: http://config-server:8888
      # 是否启用配置中心(默认true)
      enabled: true
      # 配置文件格式(properties/yml/yaml)
      profile: yml
      # 分支名称(Git仓库)
      label: master
      # 连接超时时间(毫秒)
      timeout: 5000
      # 重试配置
      retry:
        # 是否启用重试
        enabled: true
        # 初始重试间隔(毫秒)
        initial-interval: 1000
        # 最大重试间隔(毫秒)
        max-interval: 2000
        # 最大重试次数
        max-attempts: 3
    
    # 服务发现配置(如果使用 Eureka)
    discovery:
      # 是否通过服务发现获取配置中心地址
      enabled: true
      # 配置中心在服务注册中心的服务名
      service-id: config-server

# 加密/解密配置(可选)
encrypt:
  key: my-secret-key

# 日志级别配置(引导阶段)
logging:
  level:
    org.springframework.cloud: DEBUG

3.2 application.yml 示例(主配置文件)

# application.yml - 主应用配置文件
# 说明:包含应用的核心配置,会被环境特定配置覆盖
# 注意:配置中心的同名配置会覆盖此文件中的配置

# 服务器配置
server:
  # 服务端口
  port: 8080
  # 上下文路径
  servlet:
    context-path: /api
  # Tomcat 配置
  tomcat:
    # 最大线程数
    max-threads: 200
    # 最小空闲线程数
    min-spare-threads: 10
    # 连接超时时间(毫秒)
    connection-timeout: 20000

# Spring 相关配置
spring:
  # 应用基本信息
  application:
    name: user-service
    # 应用描述
    description: 用户服务模块
  
  # 数据源配置
  datasource:
    # 数据库驱动类名
    driver-class-name: com.mysql.cj.jdbc.Driver
    # 数据库连接URL
    url: jdbc:mysql://localhost:3306/user_db?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    # 数据库用户名
    username: root
    # 数据库密码
    password: password
    # 连接池配置
    hikari:
      # 连接池名称
      pool-name: UserHikariCP
      # 最大连接数
      maximum-pool-size: 20
      # 最小空闲连接数
      minimum-idle: 5
      # 连接超时时间(毫秒)
      connection-timeout: 30000
      # 空闲连接存活时间(毫秒)
      idle-timeout: 600000
      # 连接最大生命周期(毫秒)
      max-lifetime: 1800000
  
  # JPA/Hibernate 配置
  jpa:
    # 是否在启动时显示 SQL 语句
    show-sql: false
    # 数据库方言
    database-platform: org.hibernate.dialect.MySQL8Dialect
    # Hibernate DDL 自动模式
    hibernate:
      ddl-auto: update
    # 实体包扫描路径
    packages-to-scan: com.example.user.entity
  
  # Redis 配置
  redis:
    # Redis 服务器地址
    host: localhost
    # Redis 服务器端口
    port: 6379
    # 连接超时时间(毫秒)
    timeout: 5000
    # 数据库索引
    database: 0
    # 密码(如果需要)
    password: 
    # 连接池配置
    lettuce:
      pool:
        # 最大连接数
        max-active: 8
        # 最大空闲连接数
        max-idle: 8
        # 最小空闲连接数
        min-idle: 0
        # 获取连接时的最大等待时间(毫秒)
        max-wait: -1ms
  
  # 消息队列配置(RabbitMQ 示例)
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: /
    # 连接超时配置
    connection-timeout: 5000
    # 监听器配置
    listener:
      simple:
        # 并发消费者数量
        concurrency: 5
        # 最大并发消费者数量
        max-concurrency: 10
        # 每次批量消费的消息数量
        prefetch: 1
  
  # 文件上传配置
  servlet:
    multipart:
      # 是否启用文件上传
      enabled: true
      # 单个文件最大大小
      max-file-size: 10MB
      # 单次请求最大大小
      max-request-size: 100MB
  
  # 国际化配置
  messages:
    # 消息文件基础名
    basename: messages
    # 编码格式
    encoding: UTF-8

# 自定义业务配置
user:
  # 用户服务相关配置
  service:
    # 用户缓存过期时间(秒)
    cache-expire-time: 3600
    # 最大用户注册数量
    max-registration-count: 10000
    # 是否启用邮箱验证
    enable-email-verification: true
    # 邮箱验证链接有效期(小时)
    email-verification-expire-hours: 24
  
  # 第三方API配置
  third-party:
    sms:
      # 短信服务商API地址
      api-url: https://sms-api.example.com/send  
      # API密钥
      api-key: your-api-key
      # 发送超时时间(毫秒)
      timeout: 5000

# Actuator 监控端点配置
management:
  # 端点基础路径
  endpoints:
    web:
      base-path: /actuator
      exposure:
        # 暴露所有端点(生产环境建议只暴露必要的端点)
        include: "*"
  # 健康检查详细信息
  endpoint:
    health:
      show-details: always
  # 指标配置
  metrics:
    export:
      prometheus:
        enabled: true

# 日志配置
logging:
  # 日志级别配置
  level:
    # 根日志级别
    root: INFO
    # 应用包日志级别
    com.example.user: DEBUG
    # Spring Web 日志级别
    org.springframework.web: INFO
    # 数据库操作日志级别
    org.hibernate.SQL: DEBUG
  # 日志文件配置
  file:
    name: logs/user-service.log
    # 日志文件最大大小
    max-size: 10MB
    # 保留的日志文件数量
    max-history: 30

# 安全配置(Spring Security)
security:
  # JWT 配置
  jwt:
    # 密钥
    secret: my-secret-key-for-jwt
    # 过期时间(毫秒)
    expiration: 86400000
    # 头部名称
    header: Authorization

3.3 application-dev.yml 示例(开发环境配置)

# application-dev.yml - 开发环境配置文件
# 说明:此配置仅在开发环境生效
# 注意:如果配置中心有同名配置,配置中心的值会覆盖此文件

# 服务器配置(开发环境使用不同端口)
server:
  port: 8081
  servlet:
    context-path: /api

# Spring 配置
spring:
  # 数据源配置(开发环境数据库)
  datasource:
    url: jdbc:mysql://localhost:3306/user_db_dev?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai
    username: dev_user
    password: dev_password
    hikari:
      maximum-pool-size: 10
      minimum-idle: 2
  
  # Redis 配置(开发环境)
  redis:
    host: localhost
    port: 6379
    database: 1
  
  # 启用 H2 控制台(开发调试用)
  h2:
    console:
      enabled: true
      path: /h2-console
  
  # 开发环境特定的配置
  profiles:
    active: dev

# 开发环境自定义配置
user:
  service:
    # 开发环境缓存时间较短,便于调试
    cache-expire-time: 60
    # 开发环境不启用邮箱验证
    enable-email-verification: false
  third-party:
    sms:
      # 开发环境使用模拟API
      api-url: http://localhost:9000/mock-sms
      api-key: mock-api-key

# Actuator 配置(开发环境暴露更多端点)
management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

# 日志配置(开发环境显示更详细日志)
logging:
  level:
    root: DEBUG
    com.example.user: DEBUG
    org.springframework.web: DEBUG
    org.hibernate.SQL: DEBUG
    org.hibernate.type.descriptor.sql.BasicBinder: TRACE
  file:
    name: logs/user-service-dev.log

3.4 application-test.yml 示例(测试环境配置)

# application-test.yml - 测试环境配置文件
# 说明:此配置用于单元测试、集成测试和自动化测试环境

# 服务器配置(测试环境)
server:
  port: 8082
  servlet:
    context-path: /api

# Spring 配置
spring:
  # 测试环境激活配置
  profiles:
    active: test
  
  # 数据源配置(测试环境 - 使用内存数据库)
  datasource:
    # 使用 H2 内存数据库进行测试
    driver-class-name: org.h2.Driver
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
    username: sa
    password: 
    hikari:
      maximum-pool-size: 5
      minimum-idle: 1
  
  # JPA 配置(测试环境)
  jpa:
    show-sql: false
    database-platform: org.hibernate.dialect.H2Dialect
    hibernate:
      # 测试环境每次启动都重新创建表结构
      ddl-auto: create-drop
    packages-to-scan: com.example.user.entity
  
  # Redis 配置(测试环境 - 使用嵌入式 Redis 或禁用)
  redis:
    host: localhost
    port: 6380  # 测试环境使用不同的 Redis 端口
    database: 2
    timeout: 1000
    lettuce:
      pool:
        max-active: 5
        max-idle: 3
        min-idle: 1
        max-wait: 1000ms
  
  # 消息队列配置(测试环境 - 使用嵌入式 RabbitMQ 或模拟)
  rabbitmq:
    host: localhost
    port: 5673  # 测试环境使用不同的端口
    username: test
    password: test
    virtual-host: /test
  
  # 测试环境特定配置
  main:
    # 允许循环依赖(某些测试场景可能需要)
    allow-circular-references: true

# 测试环境自定义配置
user:
  service:
    # 测试环境缓存时间极短或禁用缓存
    cache-expire-time: 10
    # 测试环境不限制注册数量
    max-registration-count: 999999
    # 测试环境邮箱验证可选
    enable-email-verification: false
  third-party:
    sms:
      # 测试环境使用模拟服务
      api-url: http://localhost:9001/mock-sms-test
      api-key: test-api-key
      timeout: 1000

# Actuator 配置(测试环境)
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,env,beans
  endpoint:
    health:
      show-details: always

# 日志配置(测试环境 - 详细日志便于调试)
logging:
  level:
    root: INFO
    com.example.user: DEBUG
    org.springframework: INFO
    org.springframework.test: DEBUG
    org.hibernate.SQL: DEBUG
  file:
    name: logs/user-service-test.log
    max-size: 50MB
    max-history: 7

# 测试专用配置
test:
  # 测试数据初始化配置
  data:
    # 是否在测试前初始化测试数据
    initialize: true
    # 测试数据文件路径
    init-script: classpath:test-data.sql
  # Mock 服务配置
  mock:
    # 是否启用所有第三方服务的 Mock
    enabled: true
    # Mock 延迟时间(毫秒)
    delay: 100

3.5 application-staging.yml 示例(预发布环境配置)

# application-staging.yml - 预发布环境配置文件
# 说明:此配置用于预发布/准生产环境,配置应尽可能接近生产环境

# 服务器配置(预发布环境)
server:
  port: 8080
  servlet:
    context-path: /api
  tomcat:
    max-threads: 400
    min-spare-threads: 20
    connection-timeout: 15000
    # 预发布环境也启用 HTTPS
    ssl:
      enabled: true
      key-store: classpath:staging-keystore.p12
      key-store-password: staging-changeit
      key-store-type: PKCS12
      key-alias: tomcat

# Spring 配置
spring:
  # 预发布环境激活配置
  profiles:
    active: staging
  
  # 数据源配置(预发布环境数据库)
  datasource:
    url: jdbc:mysql://staging-db-cluster:3306/user_db_staging?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=true
    username: ${DB_USERNAME_STAGING}
    password: ${DB_PASSWORD_STAGING}
    hikari:
      maximum-pool-size: 40
      minimum-idle: 8
      connection-timeout: 20000
      idle-timeout: 300000
      max-lifetime: 1200000
      connection-test-query: SELECT 1
  
  # Redis 配置(预发布环境集群)
  redis:
    cluster:
      nodes:
        - staging-redis-1:7000
        - staging-redis-2:7001
        - staging-redis-3:7002
    timeout: 2000
    lettuce:
      pool:
        max-active: 15
        max-idle: 8
        min-idle: 3
        max-wait: 2000ms
  
  # 消息队列配置(预发布环境)
  rabbitmq:
    host: staging-rabbitmq-cluster
    port: 5672
    username: ${RABBITMQ_USERNAME_STAGING}
    password: ${RABBITMQ_PASSWORD_STAGING}
    virtual-host: /staging
    connection-timeout: 5000
    listener:
      simple:
        concurrency: 3
        max-concurrency: 8
        prefetch: 1

# 预发布环境自定义配置
user:
  service:
    # 预发布环境缓存时间接近生产环境
    cache-expire-time: 3600  # 1小时
    max-registration-count: 500000
    enable-email-verification: true
    email-verification-expire-hours: 24
  third-party:
    sms:
      # 预发布环境使用真实的第三方服务但有限制
      api-url: https://staging-sms-api.example.com/send  
      api-key: ${SMS_API_KEY_STAGING}
      timeout: 3000
      # 预发布环境短信发送限制
      rate-limit:
        max-per-minute: 10
        max-per-hour: 100

# Spring Cloud 配置(预发布环境)
spring:
  cloud:
    # 服务发现配置
    discovery:
      client:
        simple:
          instances:
            user-service:
              - uri: http://staging-user-service-1:8080
              - uri: http://staging-user-service-2:8080
    
    # 熔断器配置
    circuitbreaker:
      resilience4j:
        instances:
          userService:
            failureRateThreshold: 50
            waitDurationInOpenState: 5000
            permittedNumberOfCallsInHalfOpenState: 3
            slidingWindowSize: 10

# Actuator 配置(预发布环境)
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,env,beans,configprops
  endpoint:
    health:
      show-details: when_authorized
    env:
      enabled: true
    beans:
      enabled: true

# 日志配置(预发布环境)
logging:
  level:
    root: INFO
    com.example.user: DEBUG
    org.springframework.web: INFO
    org.hibernate.SQL: WARN
  file:
    name: /var/log/user-service/user-service-staging.log
    max-size: 100MB
    max-history: 30

# 安全配置(预发布环境)
security:
  jwt:
    secret: ${JWT_SECRET_STAGING}
    expiration: 172800000  # 2天
    header: Authorization

# 监控和告警配置
monitoring:
  # 应用性能监控
  apm:
    enabled: true
    server-url: https://staging-apm.example.com  
    service-name: user-service-staging
  # 告警配置
  alert:
    email:
      enabled: true
      recipients:
        - ops-team@example.com
        - dev-team@example.com
    thresholds:
      error-rate: 0.05  # 错误率超过5%告警
      response-time: 2000  # 响应时间超过2秒告警

3.6 application-prod.yml 示例(生产环境配置)

# application-prod.yml - 生产环境配置文件
# 说明:此配置仅在生产环境生效,包含生产环境的安全和性能优化配置

# 服务器配置(生产环境)
server:
  port: 8080
  servlet:
    context-path: /api
  tomcat:
    max-threads: 500
    min-spare-threads: 25
    connection-timeout: 10000
    # 生产环境启用 HTTPS
    ssl:
      enabled: true
      key-store: classpath:keystore.p12
      key-store-password: changeit
      key-store-type: PKCS12
      key-alias: tomcat

# Spring 配置
spring:
  # 数据源配置(生产环境)
  datasource:
    url: jdbc:mysql://prod-db-cluster:3306/user_db_prod?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=true
    username: ${DB_USERNAME}  # 从环境变量获取
    password: ${DB_PASSWORD}  # 从环境变量获取
    hikari:
      maximum-pool-size: 50
      minimum-idle: 10
      connection-timeout: 20000
      idle-timeout: 300000
      max-lifetime: 1200000
      # 生产环境连接池健康检查
      connection-test-query: SELECT 1
  
  # Redis 配置(生产环境集群)
  redis:
    cluster:
      nodes:
        - redis-cluster-1:7000
        - redis-cluster-2:7001
        - redis-cluster-3:7002
    timeout: 2000
    lettuce:
      pool:
        max-active: 20
        max-idle: 10
        min-idle: 5
        max-wait: 2000ms
  
  # 生产环境禁用 H2 控制台
  h2:
    console:
      enabled: false
  
  # 生产环境激活配置
  profiles:
    active: prod

# 生产环境自定义配置
user:
  service:
    cache-expire-time: 7200  # 2小时缓存
    max-registration-count: 1000000
    enable-email-verification: true
    email-verification-expire-hours: 48
  third-party:
    sms:
      api-url: https://prod-sms-api.example.com/send  
      api-key: ${SMS_API_KEY}  # 从环境变量获取
      timeout: 3000

# Actuator 配置(生产环境只暴露必要端点)
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus
  endpoint:
    health:
      show-details: when_authorized
    # 禁用敏感端点
    env:
      enabled: false
    beans:
      enabled: false

# 日志配置(生产环境优化)
logging:
  level:
    root: WARN
    com.example.user: INFO
    org.springframework.web: WARN
    org.hibernate.SQL: ERROR
  file:
    name: /var/log/user-service/user-service.log
    max-size: 100MB
    max-history: 90

# 安全配置
security:
  jwt:
    secret: ${JWT_SECRET}  # 从环境变量获取
    expiration: 259200000  # 3天

4. Spring Boot 2.4+ 新配置方式详解

4.1 为什么引入新方式?

  • 简化配置:无需理解 Bootstrap Context 的复杂性
  • 标准化:遵循 Spring Boot 标准配置机制
  • 更好的工具支持:IDE 配置提示更准确
  • 减少依赖:无需额外的 bootstrap 依赖

4.2 新方式配置示例

4.2.1 基础配置
# application.yml
spring:
  application:
    name: user-service
  profiles:
    active: dev
  config:
    import: 
      - optional:configserver:http://config-server:8888
4.2.2 多环境配置
# application.yml
spring:
  application:
    name: user-service
  config:
    import: 
      - optional:configserver:${CONFIG_SERVER_URL:http://localhost:8888}

# application-dev.yml  
spring:
  config:
    import: 
      - optional:configserver:http://dev-config-server:8888

# application-prod.yml
spring:
  config:
    import: 
      - configserver:http://prod-config-server:8888
4.2.3 多配置源
spring:
  config:
    import:
      - optional:configserver:http://config-server:8888
      - optional:classpath:local-overrides.yml
      - optional:file:./external-config.yml

4.3 依赖配置

Maven(新方式无需额外依赖)
<!-- 只需要 Spring Cloud Config Client -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
如果仍需使用 bootstrap.yml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

5. 注意事项与最佳实践

5.1 安全注意事项

# ❌ 错误做法:在配置文件中硬编码敏感信息
spring:
  datasource:
    password: "hardcoded_password"

# ✅ 正确做法:使用环境变量或配置中心
spring:
  datasource:
    password: ${DB_PASSWORD}

5.2 配置文件组织最佳实践

5.2.1 目录结构建议
src/main/resources/
├── application.yml           # 公共配置
├── application-dev.yml       # 开发环境
├── application-test.yml      # 测试环境
├── application-staging.yml   # 预发布环境
├── application-prod.yml      # 生产环境
└── bootstrap.yml            # Spring Cloud 引导配置(如需要)
5.2.2 配置分层原则
  • 公共配置:放在 application.yml 中
  • 环境差异配置:放在对应的 application-{profile}.yml 中
  • 敏感配置:通过环境变量、配置中心或外部文件注入
  • 引导配置:Spring Cloud 相关配置放在 bootstrap.yml 中(或使用新方式)

5.3 YAML 语法注意事项

# ✅ 正确的缩进(2个空格)
server:
  port: 8080
  servlet:
    context-path: /api

# ❌ 错误的缩进(混合使用空格和Tab)
server:
	port: 8080  # 这会导致解析错误

# ✅ 字符串值建议使用引号(特别是包含特殊字符时)
description: "用户服务 - v1.0"

# ✅ 列表配置
management:
  endpoints:
    web:
      exposure:
        include:
          - health
          - info
          - metrics

5.4 配置验证与测试

5.4.1 使用 @ConfigurationProperties 进行类型安全配置
// Java 配置类示例
@Data
@Component
@ConfigurationProperties(prefix = "user.service")
public class UserServiceProperties {
    /**
     * 用户缓存过期时间(秒)
     */
    private int cacheExpireTime = 3600;
    
    /**
     * 最大用户注册数量
     */
    private int maxRegistrationCount = 10000;
    
    /**
     * 是否启用邮箱验证
     */
    private boolean enableEmailVerification = true;
    
    /**
     * 邮箱验证链接有效期(小时)
     */
    private int emailVerificationExpireHours = 24;
}
5.4.2 配置文件验证方法
  • 启动验证:应用启动时验证配置是否正确加载
  • Actuator 端点:使用 /actuator/env 查看实际生效的配置
  • 环境测试:在各环境中充分测试配置覆盖行为
  • 配置刷新:使用 /actuator/refresh 动态刷新配置(如启用)

5.5 Spring Cloud 特定注意事项

5.5.1 bootstrap.yml 使用场景
  • 传统方式:需要显式添加 spring-cloud-starter-bootstrap 依赖
  • 新项目推荐:使用 spring.config.import 方式
  • 迁移策略:旧项目可暂时保留 bootstrap.yml,新功能使用新方式
5.5.2 配置中心最佳实践
  • 命名规范:{application-name}-{profile}.yml
  • 版本控制:使用 Git 管理配置文件,合理使用分支和标签
  • 安全管控:敏感配置通过 Vault 或环境变量管理
  • 动态刷新:合理使用 @RefreshScope 注解

6. 总结

6.1 配置文件选择指南

场景推荐方案说明
Spring Boot 单体应用application.yml + application-{profile}.yml标准配置方式
Spring Cloud 新项目spring.config.import + application.yml官方推荐方式
Spring Cloud 旧项目bootstrap.yml + application.yml + application-{profile}.yml兼容现有架构

6.2 关键原则总结

  1. 安全性原则:绝不硬编码敏感信息,使用环境变量或配置中心
  2. 环境隔离原则:不同环境使用不同 profile,避免配置污染
  3. 配置覆盖原则:配置中心配置优先级高于本地配置
  4. 类型安全原则:使用 @ConfigurationProperties 进行配置绑定
  5. 验证测试原则:确保配置在各环境中正确生效
  6. 现代化原则:新项目优先使用 Spring Boot 2.4+ 的新配置方式

6.3 版本兼容性建议

  • Spring Boot 2.4+ & Spring Cloud 2020.0+:推荐使用 spring.config.import
  • Spring Boot 2.3 及以下:继续使用 bootstrap.yml
  • 混合环境:可根据团队熟悉度和项目需求选择合适方案

通过遵循这些最佳实践和理解配置加载机制,可以构建出安全、可维护、可扩展的 Spring Boot 和 Spring Cloud 应用配置体系。

Java Spring、Spring MVC、Spring Boot 和 Spring Cloud 的关系与区别 本文详细介绍了 Java 开发中常用的 Spring 系列框架及其关系。Spring 是核心框架,提供控制反转(IoC)和面向切面编程(AOP)等基础功能。Spring MVC 是 Spring 的模块,专注于 Web 开发,采用 MVC 设计模式。Spring Boot 简化了 Spring 应用的初始搭建和开发,提供默认配置和嵌入式服务器。Spring Cloud 基于 Spring Boot,扩展了分布式系统开发的能力,提供服务发现、熔断器等功能。这些框架共同构成了强大的 Java 开发生态系统,满足 阅读详情

相关推荐

Spring Boot配置文件加密实战:Jasypt与Spring Cloud Config方案详解

在软件工程实践中,配置管理是应用安全与部署的核心环节。其原理在于将敏感信息(如数据库密码、API密钥)从明文存储转为密文,通过加解密机制在运行时动态还原,从而避免信息泄露。这项技术的核心价值在于实现安全性与便利性的平衡,既能防止代码仓库、配置中心泄露风险,又能适应持续集成与容器化部署流程。常见的应用场景包括微服务架构中的集中配置管理、金融支付系统的密钥保护以及符合安全合规要求的项目部署。本文聚焦于Spring Boot生态,深入解析Jasypt对称加密与Spring Cloud Config非对称加密两种主

weixin_33847182的博客 465

springcloud配置详解

springcloud各组件配置详解

qq_44970261的博客 1274

Spring boot与Spring cloud 之间的关系

1、Spring boot 是 Spring (AOP和IOC)的一套快速配置脚手架,可以基于spring boot 快速开发单个微服务; Spring Cloud是一个基于Spring Boot实现的云应用开发工具;Spring Cloud是多个Spring boot微服务的集合,当然不是简单的集合,那么就涉及到微服务的七大原则:1)、围绕业务概念建模经验表明,围绕业务的限界上下文定义的接口,比围绕技术概念定义的接口更加稳定。针对系统如何工作这个领域进行建模,不仅可以帮助我们形成更稳定的接口,也

CaseyWei 5884

每天学点SpringCloud(九):SpringCloud最常用配置详解

Eureka 属性名 说明 默认值 eureka.server.enable-self-preservation 关闭注册中心的保护机制,Eureka 会统计15分钟之内心跳失败的比例低于85%将会触发保护机制,不剔除服务提供者,如果关闭服务注册中心将不可用的实例正确剔除 false eureka.instance.prefer-ip-address 不使用主机名来定义...

diansheshi4163的博客 590

Spring Boot 集成 Spring Cloud 的详细教程

在 Spring Initializr 中生成一个新的 Spring Boot 项目,添加依赖 “Spring Cloud Starter Gateway” 和 “Spring Cloud Starter Netflix Eureka Client”。:在 Spring Initializr 中生成一个新的 Spring Boot 项目,添加依赖 “Spring Cloud Starter Netflix Eureka Server”。文件中配置服务的基本信息和 Eureka 服务注册中心的地址。

坚持写博客,大家的关注是我前进的动力! 1139

Spring Cloud与Spring Boot版本匹配指南

微服务架构中,Spring Cloud作为基于Spring Boot的扩展框架,其版本兼容性直接影响系统稳定性。通过BOM(物料清单)管理机制,Spring Cloud与Spring Boot形成严格的版本对应关系,这种设计既保证了自动配置等核心功能的可靠性,也避免了依赖冲突。开发实践中常见的ClassNotFoundException、Bean创建失败等问题,往往源于版本不匹配。在金融、电商等企业级应用中,正确的版本组合能确保服务注册发现、配置中心等微服务组件稳定运行。本文结合Spring Cloud 2

weixin_34393428的博客 372

【微服务 从0开始 】Spring Cloud 配置文件

详细了解如何配置Spring boot

4万+

Spring中的那些配置文件详解

Spring Boot 默认支持 properties(.properties) 和 YAML(.yml .yaml ) 两种格式的配置文件,yml 和 properties 文件都属于配置文件,功能一样。 Spring Cloud 构建于 Spring Boot 之上,在 Spring Boot 中有两种上下文,一种是 bootstrap,另外一种是 application,下面列举这两种配置文件的区别 加载顺序 若application.yml 和bootstrap.yml 在同一目录下:bootstr

流楚丶格念的博客 3243

SpringCloud组件配置解析【yml分析】

server日志:【每隔十秒进行一次删除注册】显然,这样的配置太过于繁琐,于是可以将这个admin的服务端作为eureka的客户端注册到eureka的配置中心内,然后admin就可以直接从服务端内进行客户列表的拉。【注:当想要让配置中心内的配置文件返回修改前的状态 即:回滚,可以点击 更多 ->历史版本 选项,里面存放了三十天之内的全部历史版本,存放在数据库内】直接在api的feign内进行对应方法标签的创建,然后让导入了api依赖的服务的controller类实现feign接口,再重写接口内的方法即可。

m0_73939848的博客 1814

【云原生技术】Spring Boot、Spring Cloud、JPA 设置、Spring Profiles 以及 应用配置文件的使用

通过这种结构化整理,你可以清晰地理解 Spring Boot 和 Spring Cloud 相关概念及其相互关系。这些概念涵盖了应用程序的配置、数据访问、服务管理等多个方面,为你未来的开发工作奠定了良好的基础。

weixin_46453070的博客 1997

不得不知的Spring Boot与Spring Cloud应用启动流程

Spring Cloud与Kubernetes系列文章已经更新到第十五篇,而源码分析类的文章笔者是默认大家都已经对Spring的源码所有了解了,至少什么工厂Bean、后置处理器BeanPostProcessor、Bean的生命周期、Spring容器的启动流程等都有所了解。 在继续分析Spring Cloud实现动态配置的源码之前,我们需要补充一些Spring Boot和Spring Cloud的基础知识才能继续往下看。本篇我们一起学习Spring Boot与Spring Cloud应用的启动流程。 S.

吴就业 2716

Spring、Spring Boot 和 Spring Cloud 的区别详解

在软件架构设计中,**Spring**、**Spring Boot** 和 **Spring Cloud** 是 Java 开发人员经常使用的核心框架,它们各自有着不同的功能定位和设计理念。本文将从框架特性、应用场景、优缺点等角度深入探讨它们的区别,并通过具体的开发场景加以说明。

开源AI 专属 UI——papyrai-ui。《千界明彻录》(故事形式构建元思维)——胡说小说。更多思辨内容在公众号。 3348

C++游戏开发入门:从环境配置到第一个完整项目

C++ 作为游戏开发领域的关键语言,其学习路径常因语法枯燥而令初学者却步。以项目驱动的方式学编程,能帮助学习者将变量、循环、函数、指针等基础概念融入实际游戏逻辑中,获得即时反馈与完整项目经验。掌握合适的开发环境是高效实践的前提,例如在 Windows 下使用 VS Code 搭配 MinGW-w64 编译器,配合调试器与构建脚本,即可搭建轻量可扩展的 C++ 游戏开发工作流。此类课程通常面向无基础人群,从控制台小游戏逐步过渡到带游戏循环的完整作品,过程中还需关注性能观察、素材授权与版本管理。无论你是刚接触编

weixin_30621959的博客 540

Java面试必备:Spring Boot 与 Spring Cloud 的区别详解

Spring Boot 和 Spring Cloud 都是 Spring 生态系统中的重要组成部分,但它们解决的问题和适用场景有所不同。

qq_58299462的博客 1935

CESM笔记——CESM1.0-CESM1.2.2-CESM2.1.3三个版本模式工作流对比

最近测试了CESM1.0,CESM1.2.2和CESM2.1.3三个版本,不同版本在workflow上有一些区别,来做点笔记。 CESM1.0 测试compset:B_2000,F_2000 workflow: 1. create_newcase -case ~/CESM/cesm1_0/script/B_2000 -compset B_2000 -res f19_g16 -mach tianhe 2. cd B_2000 (optional) env_mach_pes.xml ##修改核数,

砍柴姑娘Jourosy的博客 4941

STM32与威纶通触摸屏RS485通信实战:Modbus RTU协议与避坑指南

在工业自动化与嵌入式系统开发中,串行通信是实现设备间数据交换的基础技术。RS485总线凭借其差分信号传输、抗干扰能力强、支持多点通信及长距离传输等特性,成为工业现场广泛应用的物理层标准。其核心原理是利用一对双绞线进行平衡传输,有效抑制共模噪声。在协议层,Modbus RTU作为开放、简洁的主从式应用层协议,定义了统一的数据模型(如线圈、寄存器)和功能码,极大简化了不同厂商设备间的互操作性。结合STM32微控制器的UART外设与威纶通(Weinview)人机界面(HMI),可以构建稳定可靠的监控与控制系统。本

weixin_33925615的博客 327

Spring Boot 与 Spring Cloud:构建微服务应用的最佳组合

Spring Boot 提供了快速构建单个服务的能力,而 Spring Cloud 通过丰富的工具集成支持微服务架构。 Spring Boot 和 Spring Cloud 是构建分布式系统的黄金组合,适合企业级应用开发。 在实践中,要关注微服务的健壮性、性能优化以及团队协作。

一名热衷于技术的全栈开发者,专注于前端与后端的全面技术探索。在这里,我将分享我在技术领域的学习与成长,助力更多开发者的进步。 1210

Python实战:逐笔高频因子构建与回测全流程解析

本文详细解析了使用Python构建与回测逐笔高频因子的全流程。从逐笔数据的价值与清洗入手,通过实战代码演示了‘大买成交金额占比’因子的计算逻辑,并重点阐述了因子正交化处理的重要性以剔除风格影响。最后,提供了一个经典的分位数回测框架来验证因子有效性,并分享了数据质量、计算效率与过拟合等核心避坑指南。

grass的博客 391

Spring、Spring Boot、Spring Cloud 的区别与联系

Feign(声明式 HTTP 客户端)、RestTemplate + Ribbon(负载均衡)。:默认集成 Tomcat、Jetty 或 Undertow,无需部署 WAR 包。:支持 JDBC、ORM(如 Hibernate、MyBatis)。:基于 Servlet 的 MVC 框架,处理 HTTP 请求。提供分布式能力(如服务发现、配置中心、熔断)。:传统单体应用,需要精细控制配置的复杂场景。:提供应用监控端点(如健康检查、指标收集)。是基础,提供核心功能(IoC、AOP)。

guanxin0206的博客 3089

用Python玩转共现分析:从NLTK到热力图可视化(附完整代码)

本文详细介绍了如何使用Python进行文本共现分析,从NLTK基础文本处理到构建共现矩阵,并实现热力图可视化。通过完整的代码示例,帮助数据分析师和开发者掌握这一揭示词语间关联网络的实用NLP技术,快速从文本中提取语义关系和主题结构。

weixin_29313817的博客 347

八、ILI2511 初版调试

8.1 TP成品过程 TP厂在制造TP过程中会经过FPC、FOG和Model三个阶段。 FPC: 将IC做在FPC上面; FOG: 将FPC与sensor 绑定; Model:FOG阶段后,贴上CG(cover glass)。 经过上面三个阶段后,将会拿到没有烧录固件的TP模组。这个时候触摸TP,并不能上报触摸数据,需要对TP模组烧录固件(执行程序)后才会有TP有触摸数据。 8.2 源码编译固件与工具生成固件 我们可以通过以下两种方式获得固件 1)由奕力原厂直接通过源码,进行编...

qq_34343637的博客 3685

Spring Cloud Alibaba与Spring Boot、Spring Cloud版本对应关系

在搭建项目环境架构的时候,需要选择SpringBoot和进行兼容的版本号,因此对于选择SpringBoot版本与版本的对应关系很重要,如果版本关系不对应,常见的会遇见项目启动不起来,怪异的则会是你的项目出现一些诡异的问题,查资料也不好查。下面就收集一下SpringBoot与版本之间的对应关系,在搭建项目框架或者学习时按照对应的版本区间进行选择即可,避免走一些不必要的弯路。

web15285868498的博客 3093

heygem本地部署报错:SQLite3 can only bind numbers, strings, bigints, buffers, and null...如何解决?

🏆本文收录于 《全栈Bug调优(实战版)》 专栏,该专栏专注于分享我在真实项目开发中遇到的各类疑难Bug及其深层成因,并系统提供高效、可复现的解决思路和实操方案。无论你是刚入行的新手开发者,还是拥有多年项目经验的资深工程师,本专栏都将为你提供一条系统化、高质量的问题排查与优化路径,助力你加速成长,攻克技术壁垒,迈向技术价值最大化与职业发展的更高峰🚀!    📌 特别说明: 文中部分技术问题来源于真实生产环境及网络公开案例,均经过精挑细选与系统化整理,并结合多位大厂资深架构师和一线开发多年实战经验沉淀,

**My Coding Family** 3246

浅析Spring boot与Spring cloud 之间的关系

浅析Spring boot与Spring cloud 之间的关系 2018-05-15 18:16:10有些童鞋刚接触这块 ,理解不是很深刻会经常问道这样类似的问题,下面我就简单讲解一下Spring boot与Spring cloud 之间的关系!Spring boot 是 Spring 的一套快速配置脚手架,可以基于spring boot 快速开发单个微服务,Spring Boot,看名字就知道...

勇仔博客 11万+

IEC61850规约客户端软件开发实战(第二章)

本文介绍了基于IEC61850规约的客户端软件开发过程,重点阐述功能界面设计和服务端连接功能的实现。界面采用Qt框架设计,包含功能按钮区、数据模型展示区(使用QTreeWidget)和状态显示区。连接功能通过libiec61850开源库实现,详细说明了连接流程、句柄创建及状态管理的代码实现。测试结果表明系统能正确识别连接状态,并通过界面直观显示。文章为IEC61850规约软件开发提供了实用参考,下期将分享规约模型数据加载的实现过程。

半青年的博客 2854

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

Spring Cloud Alibaba与Spring Boot、Spring Cloud之间不得不说的版本关系

点击蓝色“程序猿DD”关注我哟 赠书活动进行中:福利 | 3月开学季,赠书 这篇博文是临时增加出来的内容,主要是由于最近连载《Spring Cloud Alibaba基础教程》系列的时候,碰到读者咨询的大量问题中存在一个比较普遍的问题:版本的选择。其实这类问题,在之前写Spring Cloud基础教程的时候,就已经在博客中发过一篇《聊聊Spring Cloud版本的那些事儿》(htt...

程序猿DD 1492

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: IntelliJ IDEA 首次安装后推荐的插件完整指南
下一篇: Spring Boot 3 + Spring Cloud 2024 + Nacos 配置中心完整指南
龙茶清欢
博客等级 码龄7年 3720粉丝 375原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值