当前位置: 代码网 > it编程>编程语言>Java > SpringBoot配置从入门到精通(终极指南)

SpringBoot配置从入门到精通(终极指南)

2026年08月16日 Java 我要评论
这是一份非常详细、实用、通俗易懂,权威、全面的spring boot配置文件全面指南,包含了从基础到高级的各个方面,并附有可直接运行的代码示例。spring boot配置文件全面指南1. spring

这是一份非常详细、实用、通俗易懂,权威、全面的spring boot配置文件全面指南,包含了从基础到高级的各个方面,并附有可直接运行的代码示例。

spring boot配置文件全面指南

1. spring boot配置文件概述

1.1 配置文件的作用与重要性

spring boot的核心设计理念之一是“约定优于配置”,旨在减少大量的xml配置。然而,应用程序总需要根据不同的运行环境(开发、测试、生产)或特定需求进行调整。配置文件就是存放这些可调整参数的地方。它们允许开发者在不修改代码的情况下,灵活地改变应用的行为,如数据库连接信息、服务器端口、日志级别、功能开关等。这使得应用具有更好的可移植性可维护性

1.2 配置文件的类型:.properties 与 .yml/.yaml

spring boot支持两种主要的配置文件格式:

.properties 文件: 传统的java属性文件格式。使用 key=value 的形式,每行一个配置项。对于简单的扁平化配置很直接。

server.port=8080
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=secret

.yml.yaml 文件: 基于yaml (yaml ain't markup language) 格式。使用缩进来表示层级关系,结构更清晰,尤其适合表达复杂的、嵌套的配置信息。它已成为spring boot社区的推荐格式。

server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: secret

1.3 配置文件加载顺序与优先级

spring boot会从多个位置加载配置文件,并且后加载的配置会覆盖先加载的配置中相同的属性。了解这个顺序对于诊断配置问题和理解最终生效的值至关重要。详细的加载顺序将在第5节阐述。

2. 核心配置文件详解:application.properties 与 application.yml

spring boot会自动在项目的类路径(通常是 src/main/resources)下查找名为 application.propertiesapplication.yml(或 application.yaml)的文件作为主配置文件。

2.1 .properties 文件格式与语法

  • 基本结构: key=value
  • key 通常采用小写字母、数字、点. 和连字符 - 组成,点 . 用于表示层级关系(如 spring.datasource.url)。
  • value 可以是字符串、数字、布尔值(true/false)等。
  • 支持使用 #! 进行注释。
  • 示例:
    # 服务器配置
    server.port=8080
    server.servlet.context-path=/myapp
    # 数据库配置
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.driver
    spring.datasource.url=jdbc:mysql://localhost:3306/testdb?usessl=false&servertimezone=utc
    spring.datasource.username=dev_user
    spring.datasource.password=dev_pass
    # 日志配置
    logging.level.root=info
    logging.level.com.example.myapp=debug

2.2 .yml/.yaml 文件格式与语法 (yaml简介)

yaml 是一种人类友好的数据序列化标准,依赖于缩进(空格,不要用tab)来表示数据结构。

  • 键值对: 使用 key: value 表示。冒号 : 后必须有空格。
  • 层级结构: 使用缩进表示层级。相同缩进级别的键属于同一层级。
  • 列表/数组: 使用短横线 - 开头表示列表项,每个 - 后应有空格。
    my:
      list:
        - item1
        - item2
        - item3
  • 行内列表/数组: 使用方括号 []
    my.list: [item1, item2, item3]
  • 对象/map: 可以使用嵌套缩进表示,也可以使用行内花括号 {}
    my:
      map:
        key1: value1
        key2: value2
    # 或者
    my.map: {key1: value1, key2: value2}
  • 多行字符串: 可以使用 |(保留换行)或 >(折叠换行)。
    description: |
      this is a long
      multi-line string
      that preserves newlines.
    folded: >
      this is a long string
      that will be folded into
      a single paragraph.
  • 支持的数据类型: 字符串、布尔值(true/false, yes/no, on/off)、整数、浮点数、null (null~)。
  • 注释: 使用 #
  • 示例 (等效于上面的 .properties 示例):
    # 服务器配置
    server:
      port: 8080
      servlet:
        context-path: /myapp
    # 数据库配置
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.driver
        url: jdbc:mysql://localhost:3306/testdb?usessl=false&servertimezone=utc
        username: dev_user
        password: dev_pass
    # 日志配置
    logging:
      level:
        root: info
        com.example.myapp: debug

2.3 配置项的结构化表示 (yaml优势)

yaml 通过缩进清晰地展现了配置项的层级关系。例如,spring.datasource.url.properties 中是一个扁平字符串,而在 yaml 中,url 明显是 datasource 的子属性,而 datasource 又是 spring 的子属性。这种结构使得配置文件更容易阅读和维护,特别是当配置项很多且具有复杂嵌套时。

2.4 基础数据类型配置示例

以下是一些常见基础数据类型的配置示例:

# 字符串
app.name: my spring boot application
# 整数
app.max-threads: 10
# 布尔值
app.feature.enabled: true
# 浮点数
app.threshold: 0.75
# 列表/数组
app.supported-languages:
  - en-us
  - zh-cn
  - fr-fr
# map/对象
app.default-settings:
  theme: dark
  notifications: true
  timeout: 30

3. 读取配置值

将配置文件中定义的值注入到应用程序代码中是关键步骤。spring boot提供了两种主要方式:

3.1 使用 @value 注解注入单个值

  • 直接在字段、构造函数或方法参数上使用 @value("${property.name}")
  • 适用于注入简单的、分散的配置值。
  • 示例:
    import org.springframework.beans.factory.annotation.value;
    import org.springframework.stereotype.component;
    @component
    public class myservice {
        @value("${app.name}") // 注入 app.name 的值
        private string appname;
        @value("${server.port}") // 注入 server.port 的值
        private int serverport;
        @value("${app.feature.enabled:false}") // 带默认值,如果属性不存在则使用 false
        private boolean isfeatureenabled;
        public void printconfig() {
            system.out.println("application name: " + appname);
            system.out.println("server port: " + serverport);
            system.out.println("feature enabled: " + isfeatureenabled);
        }
    }

3.2 使用 @configurationproperties 注解绑定到javabean

  • 创建一个普通的java类(pojo),定义与配置项匹配的字段及其getter/setter方法。
  • 在类上添加 @configurationproperties(prefix = "your.prefix") 注解,指定配置项的前缀。
  • 将该类注册为spring bean(通常通过在主类或配置类上添加 @enableconfigurationproperties(yourconfigclass.class),或者在配置类本身使用 @component)。
  • 这种方式提供了类型安全的配置访问。spring boot会自动将配置文件(.properties.yml)中以指定前缀开头的属性绑定到这个bean的字段上。
  • 非常适合组织一组相关的配置属性。
  • 示例: 配置文件 (application.yml):
    app:
      mail:
        host: smtp.example.com
        port: 587
        username: user@example.com
        password: securepass
        protocol: smtp
        default-recipients:
          - admin@example.com
          - support@example.com
    java 配置类:
    import org.springframework.boot.context.properties.configurationproperties;
    import org.springframework.stereotype.component;
    import java.util.list;
    @component // 注册为bean
    @configurationproperties(prefix = "app.mail") // 绑定以 app.mail 开头的属性
    public class mailproperties {
        private string host;
        private int port;
        private string username;
        private string password;
        private string protocol;
        private list<string> defaultrecipients;
        // 必须提供getter和setter方法,spring通过它们进行绑定
        public string gethost() {
            return host;
        }
        public void sethost(string host) {
            this.host = host;
        }
        public int getport() {
            return port;
        }
        public void setport(int port) {
            this.port = port;
        }
        public string getusername() {
            return username;
        }
        public void setusername(string username) {
            this.username = username;
        }
        public string getpassword() {
            return password;
        }
        public void setpassword(string password) {
            this.password = password;
        }
        public string getprotocol() {
            return protocol;
        }
        public void setprotocol(string protocol) {
            this.protocol = protocol;
        }
        public list<string> getdefaultrecipients() {
            return defaultrecipients;
        }
        public void setdefaultrecipients(list<string> defaultrecipients) {
            this.defaultrecipients = defaultrecipients;
        }
    }
    使用配置类:
    import org.springframework.beans.factory.annotation.autowired;
    import org.springframework.stereotype.service;
    @service
    public class emailservice {
        private final mailproperties mailproperties;
        @autowired // 自动注入 mailproperties bean
        public emailservice(mailproperties mailproperties) {
            this.mailproperties = mailproperties;
        }
        public void sendemail() {
            // 使用 mailproperties.gethost(), mailproperties.getusername() 等来配置邮件发送器
            system.out.println("sending email using host: " + mailproperties.gethost());
            system.out.println("default recipients: " + mailproperties.getdefaultrecipients());
        }
    }

3.3 类型安全配置属性的优势

使用 @configurationproperties 的主要好处是类型安全。编译器可以帮助检查字段类型,ide可以提供代码补全(结合配置元数据,见第8节)。如果配置文件中的值无法转换为目标类型(例如,将 abc 赋值给 int 类型的字段),应用启动时会失败,这有助于及早发现配置错误。

3.4 处理复杂类型(list, map)

@configurationproperties 能够自动处理复杂类型:

  • list/数组: 如上面 mailproperties 中的 defaultrecipients。在配置文件中可以使用yaml列表格式或 .properties 中使用逗号分隔的值(需要字段类型为 list 或数组)。
  • map: 定义一个 map<string, string> 或其他类型的字段。在配置文件中可以使用嵌套键值对。
    app:
      settings:
        key1: value1
        key2: value2
    @configurationproperties(prefix = "app")
    public class appproperties {
        private map<string, string> settings;
        // getter and setter
    }

3.5 默认值与占位符 (${})

  • 默认值:@value 注解中,可以使用 :defaultvalue 的语法提供默认值(如 @value("${some.prop:default}"))。如果 some.prop 不存在,则使用 default
  • 占位符: 可以在配置文件中使用 ${} 引用其他配置项的值或系统属性、环境变量。例如:
    app:
      greeting: hello, ${user.name:world}! # 使用系统属性 user.name,如果不存在则用 'world'
    database.url = jdbc:mysql://${db_host:localhost}:3306/mydb # 使用环境变量 db_host,如果不存在则用 localhost

4. 多环境配置 (profile)

4.1 为什么需要多环境配置?

一个应用程序通常需要在不同的环境中运行,例如:

  • 开发环境 (dev): 本地开发,使用本地数据库,开启调试日志。
  • 测试环境 (test): 集成测试或qa测试,使用测试数据库。
  • 生产环境 (prod): 线上运行,使用生产数据库,高安全性和性能配置。 每个环境可能需要不同的数据库连接、服务器端口、日志级别、外部服务地址等。使用profile可以轻松管理这些环境特定的配置。

4.2 创建特定环境的配置文件

除了主配置文件 application.properties/yml,你可以创建命名为 application-{profile}.properties/yml 的文件。例如:

  • application-dev.yml - 开发环境配置
  • application-test.yml - 测试环境配置
  • application-prod.yml - 生产环境配置

这些文件通常也放在 src/main/resources 目录下。

4.3 激活profile的方式

需要明确告诉spring boot当前激活哪个(或哪些)profile,它才会加载对应的配置文件。

4.3.1 配置文件指定 (spring.profiles.active): 在主配置文件 (application.properties/yml) 中设置激活的profile。

# application.properties
spring.profiles.active=dev
# application.yml
spring:
  profiles:
    active: dev

注意:这种方式在打包后不易修改环境。

4.3.2 命令行参数 (--spring.profiles.active=): 在启动应用时通过命令行参数指定。

java -jar myapp.jar --spring.profiles.active=prod

这是非常灵活且常用的方式,特别是在生产环境部署时。

4.3.3 系统环境变量: 设置操作系统环境变量 spring_profiles_active

# linux/macos
export spring_profiles_active=prod
# windows
set spring_profiles_active=prod

然后运行应用。

4.3.4 jvm系统属性 (-d): 在启动jvm时设置系统属性。

java -dspring.profiles.active=test -jar myapp.jar

4.4 默认配置与profile特定配置的合并规则

  • application.properties/yml 中的配置是默认配置,无论激活哪个profile都会被加载。
  • 当激活某个profile(如 prod)时,spring boot会同时加载 application.properties/ymlapplication-prod.properties/yml
  • 如果同一个配置项在两个文件中都存在,则 application-prod.properties/yml 中的值会覆盖 application.properties/yml 中的值。
  • 这允许你在默认配置中定义通用设置,在profile特定配置中只定义需要覆盖或环境特有的设置。

4.5 多profile同时激活

可以同时激活多个profile,配置项之间用逗号分隔。例如 --spring.profiles.active=dev,debug。spring boot会加载 application-dev.ymlapplication-debug.yml。如果多个profile特定配置文件定义了相同的属性,后列出的profile优先级更高(例如,debug 中的配置会覆盖 dev 中的相同配置)。

5. 配置文件的位置与加载优先级

spring boot会从以下位置(按优先级从高到低)查找 application.propertiesapplication.yml 文件:

  1. 当前目录的 /config 子目录: 应用运行的工作目录下的 config 目录。
  2. 当前目录: 应用运行的工作目录。
  3. 类路径下的 /config 包: 项目打包后 classpath:/config/
  4. 类路径根目录: 项目打包后 classpath:/

优先级规则:

  • 位置1 > 位置2 > 位置3 > 位置4。同一个位置中,.properties 文件的优先级高于 .yml 文件(如果两者都存在)。
  • profile特定文件 (如 application-dev.yml) 总是与其对应的非profile文件 (如 application.yml) 一起加载。 profile特定文件可以存在于上述任何位置,其优先级规则与非profile文件相同。例如,classpath:/config/application-prod.yml 会覆盖 classpath:/application-prod.yml

5.2 指定自定义配置文件位置 (spring.config.location)

你可以使用 spring.config.location 属性来完全覆盖默认的搜索路径。

这通常在测试或特殊部署场景下使用。

  • 命令行参数:
    java -jar myapp.jar --spring.config.location=classpath:/default/,file:./custom-config/
    • classpath:/default/:在类路径的 /default/ 目录下查找。
    • file:./custom-config/:在文件系统当前目录下的 custom-config 目录中查找。
  • 系统属性或环境变量: 设置 spring.config.location
  • 注意: 当指定 spring.config.location 时,默认的配置位置会被完全禁用。如果需要保留默认位置作为后备,应使用 spring.config.additional-location

6. 外部化配置

spring boot的外部化配置机制允许从多种来源获取配置属性。按照优先级从高到低排序:

  1. 命令行参数: 通过 --key=value 传递的参数。例如 --server.port=9090
  2. 来自 spring_application_json 的属性: 内嵌在环境变量或系统属性 spring_application_json 中的json内容。
  3. 系统属性 (java -dkey=value): 通过 system.getproperties() 获取。
  4. 操作系统环境变量: 通过 system.getenv() 获取。
  5. profile-specific 配置文件 (application-{profile}.properties/yml): 仅当对应的profile激活时加载。
  6. 配置文件 (application.properties/yml): 在默认或指定位置加载。
  7. @configuration 类上的 @propertysource 注解: 显式加载自定义属性文件。例如:
    @configuration
    @propertysource("classpath:custom.properties") // 加载 classpath 下的 custom.properties
    public class appconfig {
        // ...
    }
    注意:这个文件不会被自动命名为 application 的文件覆盖规则处理。它只是添加了一个额外的 propertysource
  8. 默认属性 (springapplication.setdefaultproperties): 在代码中设置的默认值,优先级最低。
    @springbootapplication
    public class myapp {
        public static void main(string[] args) {
            springapplication app = new springapplication(myapp.class);
            properties defaultprops = new properties();
            defaultprops.setproperty("some.default.key", "defaultvalue");
            app.setdefaultproperties(defaultprops);
            app.run(args);
        }
    }

当一个属性在多个来源中被定义时,优先级高的来源中的值会覆盖优先级低来源中的值

7. 配置加密与安全

7.1 为什么需要加密敏感配置?

配置文件(尤其是源代码仓库中的)可能包含敏感信息,如数据库密码、api密钥、加密密钥等。将这些信息以明文形式存储存在安全风险。配置加密旨在保护这些敏感数据。

7.2 jasypt简介

jasypt (java simplified encryption) 是一个java库,提供简单的api用于加密文本(如配置文件中的值)。它可以与spring boot轻松集成。

7.3 使用jasypt加密配置值

  1. 添加依赖:pom.xml 中加入jasypt spring boot starter。
    <dependency>
        <groupid>com.github.ulisesbocchio</groupid>
        <artifactid>jasypt-spring-boot-starter</artifactid>
        <version>3.0.5</version> <!-- 检查最新版本 -->
    </dependency>
  2. 加密你的值: 使用jasypt提供的工具类或命令行工具加密原始明文。你需要一个加密密钥 (password)。
    • 简单java代码示例:
      import org.jasypt.encryption.pbe.standardpbestringencryptor;
      public class jasyptencryptor {
          public static void main(string[] args) {
              standardpbestringencryptor encryptor = new standardpbestringencryptor();
              encryptor.setpassword("mysecretkey"); // 设置加密密钥,务必保密!
              string encryptedtext = encryptor.encrypt("mysecretpassword"); // 加密
              system.out.println("encrypted: " + encryptedtext);
              string plaintext = encryptor.decrypt(encryptedtext); // 解密(验证)
              system.out.println("decrypted: " + plaintext);
          }
      }
    运行后得到加密后的字符串(如 4s43kh2sqqv6rqg8ak3l7w==)。
  3. 在配置文件中使用加密值:enc() 包裹加密后的字符串。
    spring:
      datasource:
        password: enc(4s43kh2sqqv6rqg8ak3l7w==) # 加密后的密码
  4. 提供加密密钥给应用: spring boot需要知道密钥才能解密。绝对不能将密钥硬编码在代码或配置文件中! 安全的方式:
    • 系统环境变量: 设置环境变量 jasypt_encryptor_password=mysecretkey
    • 命令行参数: --jasypt.encryptor.password=mysecretkey
    • 安全配置服务器: 在更复杂的系统中,密钥可能存储在专门的秘密管理服务中。

7.4 注意事项 (密钥管理)

  • 密钥安全至关重要: 泄露密钥意味着所有加密数据都可以被解密。务必使用安全的密钥传递方式(环境变量、命令行参数、密钥管理服务)。
  • 避免在版本控制中提交密钥: 使用 .gitignore 排除包含明文密钥或未加密敏感信息的配置文件。对于加密后的值,虽然可以提交,但密钥本身绝不能提交。
  • 考虑密钥轮换: 定期更换密钥以提高安全性。

8. 配置元数据 (configuration metadata)

8.1 什么是配置元数据?

配置元数据是一个json文件 (meta-inf/spring-configuration-metadata.json),它描述了应用程序支持的配置属性(特别是那些通过 @configurationproperties 绑定的属性)。它提供了:

  • 属性名称
  • 数据类型
  • 描述信息
  • 默认值
  • 是否弃用等

8.2 spring-boot-configuration-processor 的作用

这个注解处理器在编译时运行。它会扫描项目中带 @configurationproperties 注解的类,并自动生成 spring-configuration-metadata.json 文件。

  • 添加依赖:pom.xmldependencies 中加入(通常作用域为 optionalprovided,因为它只在编译时需要):
    <dependency>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-configuration-processor</artifactid>
        <optional>true</optional>
    </dependency>
  • 编译项目后,生成的 spring-configuration-metadata.json 会出现在 target/classes/meta-inf/ 目录下。

8.3 自定义配置属性的元数据提示 (ide自动补全)

生成的元数据文件使得ide(如 intellij idea, sts)能够:

  • application.properties/yml 文件中提供代码补全
  • 显示属性的描述信息数据类型
  • 标记废弃的属性。
  • 这极大地提升了开发体验和配置的准确性。

你可以通过javadoc或特定的注解 (@deprecatedconfigurationproperty) 为你的 @configurationproperties 字段添加描述和弃用信息,这些信息会被处理器捕获并写入元数据文件。

9. 最佳实践与高级技巧

9.1 组织大型配置的策略

  • 使用 @configurationproperties 分组: 将相关的配置项绑定到不同的配置类中,每个类使用不同的 prefix
  • 多文件拆分: 对于非常大的配置,可以在主配置文件 (application.yml) 中使用 spring.config.import 导入其他配置文件(spring boot 2.4+)。
    spring:
      config:
        import:
          - optional:classpath:extra-config.yml
          - optional:file:/path/to/external-config.yml
  • 环境变量优先: 对于敏感信息或经常变化的值,优先考虑使用环境变量或命令行参数。

9.2 使用 @configurationproperties 验证配置值

可以在配置类的字段上使用jsr-303 (bean validation) 注解(如 @notnull, @min, @max, @pattern, @valid)进行验证。如果配置值不符合要求,应用启动将失败。

@configurationproperties(prefix = "app.validation")
@component
public class validationproperties {
    @notnull
    private string requiredfield;
    @min(1)
    @max(100)
    private int numberbetween1and100;
    @pattern(regexp = "^[a-za-z0-9]+$")
    private string alphanumericstring;
    @valid // 用于验证嵌套对象
    private nestedproperties nested;
    // ... getters and setters
    public static class nestedproperties {
        @notblank
        private string nestedfield;
        // ... getter and setter
    }
}

9.3 配置热加载/动态刷新 (@refreshscope)

在spring cloud config等场景下,你可能希望在不重启应用的情况下更新配置。对于使用 @value@configurationproperties 注入的bean,可以添加 @refreshscope 注解。当配置服务器通知配置变更时,这些bean会被刷新(重新创建并注入新值)。

@service
@refreshscope // 标记这个bean需要在配置刷新时重建
public class refreshableservice {
    @value("${dynamic.config}")
    private string dynamicconfig;
    @autowired
    private refreshableproperties properties;
    // ...
}
@configurationproperties(prefix = "app.refresh")
@refreshscope // 配置属性类本身也可以被刷新
@component
public class refreshableproperties {
    // ...
}

9.4 自定义propertysource

你可以实现自己的 propertysource 来从任意来源加载配置(如数据库、远程http服务、自定义文件格式)。通常需要实现 propertysource 接口并将其添加到 environment 中。这是一个相对高级的主题。

9.5 避免硬编码,拥抱配置

养成习惯,将可能变化的参数(阈值、开关、地址、凭证)提取到配置文件中。这遵循了软件设计的“分离关注点”原则,使代码更灵活、更易于维护和测试。

10. 实战案例

案例1:多环境数据库配置 (开发、测试、生产)

  • 默认配置 (application.yml): 定义通用部分或开发环境配置(如果开发是默认)。
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.driver # mysql驱动
        # url, username, password 在环境特定配置中定义
    logging:
      level:
        root: info
  • 开发环境 (application-dev.yml):
    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/dev_db?usessl=false&servertimezone=utc
        username: dev_user
        password: dev_pass
  • 测试环境 (application-test.yml):
    spring:
      datasource:
        url: jdbc:mysql://test-db-server:3306/test_db?usessl=false&servertimezone=utc
        username: test_user
        password: test_pass
  • 生产环境 (application-prod.yml):
    spring:
      datasource:
        url: jdbc:mysql://prod-db-server:3306/prod_db?usessl=true&servertimezone=utc
        username: ${db_user} # 建议从环境变量获取
        password: ${db_password} # 建议从环境变量获取,或使用加密
    # 生产环境日志级别通常更高
    logging:
      level:
        root: warn
        com.example.myapp: info
  • 激活环境: 使用命令行启动生产环境应用:
    java -jar myapp.jar --spring.profiles.active=prod

案例2:集成第三方服务 (邮件服务器配置)

  • 配置文件 (application.yml):
    app:
      mail:
        host: smtp.sendgrid.net
        port: 587
        username: apikey # sendgrid使用apikey作为用户名
        password: sg.your_actual_sendgrid_api_key_here # 实际应加密或从环境变量获取
        from: no-reply@example.com
        properties: # javamail会话属性
          mail:
            smtp:
              auth: true
              starttls:
                enable: true
  • 配置类 (mailproperties): (同第3.2节示例)
  • 使用配置发送邮件 (简化示例):
    @service
    public class emailservice {
        private final mailproperties mailproperties;
        @autowired
        public emailservice(mailproperties mailproperties) {
            this.mailproperties = mailproperties;
        }
        public void sendsimplemessage(string to, string subject, string text) {
            javamailsenderimpl mailsender = new javamailsenderimpl();
            mailsender.sethost(mailproperties.gethost());
            mailsender.setport(mailproperties.getport());
            mailsender.setusername(mailproperties.getusername());
            mailsender.setpassword(mailproperties.getpassword());
            // 设置javamail会话属性
            properties props = new properties();
            props.putall(mailproperties.getproperties()); // 将yml中的properties map放入
            mailsender.setjavamailproperties(props);
            simplemailmessage message = new simplemailmessage();
            message.setfrom(mailproperties.getfrom());
            message.setto(to);
            message.setsubject(subject);
            message.settext(text);
            mailsender.send(message);
        }
    }

案例3:自定义复杂配置对象与验证

  • 配置文件 (application.yml):
    app:
      cache:
        specs:
          usercache:
            ttl: 300 # 5 minutes
            maxsize: 1000
          productcache:
            ttl: 3600 # 1 hour
            maxsize: 5000
  • 配置类 (cacheproperties):
    import org.springframework.boot.context.properties.configurationproperties;
    import org.springframework.stereotype.component;
    import org.springframework.validation.annotation.validated;
    import javax.validation.constraints.min;
    import javax.validation.constraints.notnull;
    import java.util.map;
    @component
    @configurationproperties(prefix = "app.cache")
    @validated // 启用类级别的验证
    public class cacheproperties {
        @notnull // 确保specs存在
        private map<string, cachespec> specs;
        // ... getter and setter for specs
        public static class cachespec {
            @min(60) // ttl至少60秒
            private long ttl = 60; // 默认值60秒
            @min(1) // 大小至少1
            private int maxsize = 100; // 默认值100
            // ... getters and setters
        }
    }
  • 使用配置创建缓存 (简化示例):
    @service
    public class cachemanagerservice {
        private final cacheproperties cacheproperties;
        private final map<string, cache> caches = new concurrenthashmap<>();
        @autowired
        public cachemanagerservice(cacheproperties cacheproperties) {
            this.cacheproperties = cacheproperties;
            initializecaches();
        }
        private void initializecaches() {
            cacheproperties.getspecs().foreach((name, spec) -> {
                // 根据spec创建缓存实例 (伪代码)
                cache cache = new cache(name, spec.getttl(), spec.getmaxsize());
                caches.put(name, cache);
            });
        }
        public cache getcache(string name) {
            return caches.get(name);
        }
    }

案例4:使用jasypt加密数据库密码

  • 加密密码: 使用jasypt工具加密生产数据库密码(假设明文密码是 prod_secret,加密密钥是 securekey123)。
    // 代码示例见第7.3节,得到加密字符串如 "yld4e8vvu3wvzxal5jk7/w=="
  • 配置文件 (application-prod.yml):
    spring:
      datasource:
        url: jdbc:mysql://prod-db:3306/prod_db
        username: prod_user
        password: enc(yld4e8vvu3wvzxal5jk7/w==) # 使用enc()包裹加密值
  • 启动应用并提供密钥:
    # 通过环境变量提供密钥
    export jasypt_encryptor_password=securekey123
    java -jar myapp.jar --spring.profiles.active=prod
    # 或者通过命令行参数提供密钥
    java -jar myapp.jar --spring.profiles.active=prod --jasypt.encryptor.password=securekey123

这份指南涵盖了spring boot配置文件的核心概念、使用方式、高级特性和实战案例。请根据你的实际项目需求进行应用和调整。

到此这篇关于springboot配置从入门到精通(终极指南)的文章就介绍到这了,更多相关springboot配置内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com