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

 更新时间:2026年08月14日 16:19:50   作者:索荣荣  
Spring Boot 是基于 Spring 框架的一个快速开发框架,它简化了新 Spring 应用的初始搭建以及开发过程,下面是一个从入门到精通的 Spring Boot配置指南,涵盖基础到高级配置,感兴趣的朋友一起看看吧

这是一份非常详细、实用、通俗易懂,权威、全面的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.properties 或 application.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/yml 和 application-prod.properties/yml。
  • 如果同一个配置项在两个文件中都存在,则 application-prod.properties/yml 中的值会覆盖 application.properties/yml 中的值。
  • 这允许你在默认配置中定义通用设置,在Profile特定配置中只定义需要覆盖或环境特有的设置。

4.5 多Profile同时激活

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

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

Spring Boot会从以下位置(按优先级从高到低)查找 application.properties 或 application.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.xml 的 dependencies 中加入(通常作用域为 optional 或 provided,因为它只在编译时需要):
    <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配置内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java调用Deepseek实现项目代码审查

    Java调用Deepseek实现项目代码审查

    这篇文章主要为大家详细介绍了Java如何调用Deepseek实现项目代码审查功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2025-02-02
  • Java中四种线程池的使用示例详解

    Java中四种线程池的使用示例详解

    这篇文章主要给大家介绍了关于Java中四种线程池的使用方法,四种线程池分别包括FixedThreadPool、CachedThreadPool、ScheduledThreadPool以及SingleThreadExecutor,文中给出了详细的示例代码供大家参考,需要的朋友们下面来一起看看吧。
    2017-08-08
  • Springboot中com.mysql.cj.jdbc.Driver在yml文件中爆红的原因解读

    Springboot中com.mysql.cj.jdbc.Driver在yml文件中爆红的原因解读

    这篇文章主要介绍了Springboot中com.mysql.cj.jdbc.Driver在yml文件中爆红的原因解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-05-05
  • 探讨Java 将Markdown文件转换为Word和PDF文档

    探讨Java 将Markdown文件转换为Word和PDF文档

    这篇文章主要介绍了Java 将Markdown文件转换为Word和PDF文档,本文通过分步指南及代码示例展示了如何将 Markdown 文件转换为 Word 文档和 PDF 文件,需要的朋友可以参考下
    2024-07-07
  • 浅谈JVM内存溢出的几种方式与解决方法

    浅谈JVM内存溢出的几种方式与解决方法

    内存溢出分为两大类:OutOfMemoryError和StackOverflowError,以下举出10个内存溢出的情况,并通过实例代码的方式讲解了是如何出现内存溢出的,感兴趣的可以了解一下
    2024-01-01
  • jconsole使用介绍(图文)

    jconsole使用介绍(图文)

    大家在学习java的时候,难免会对jvm进行一些深入的了解。推荐大家使用jdk下面的jconsole.exe来辅助理解jvm的一些概念
    2015-12-12
  • kaptcha验证码使用方法详解

    kaptcha验证码使用方法详解

    这篇文章主要为大家详细介绍了kaptcha验证码的使用方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-12-12
  • Java多线程实现之Callable详解

    Java多线程实现之Callable详解

    这篇文章主要介绍了Java多线程实现之Callable详解,Callable是一个接口,用于实现多线程,与实现Runnable类似,但是功能更强大,通过实现Callable接口,我们需要重写call()方法,该方法可以在任务结束后提供一个返回值,需要的朋友可以参考下
    2023-08-08
  • idea新建springboot项目的方法

    idea新建springboot项目的方法

    这篇文章主要介绍了idea新建springboot项目的方法,文中讲解非常细致,图文并茂帮助大家更好的理解学习,感兴趣的朋友可以了解下
    2020-06-06
  • 基于SpringBoot制作一个PDF切图小工具

    基于SpringBoot制作一个PDF切图小工具

    这篇文章主要为大家详细介绍了如何基于SpringBoot制作一个PDF切图小工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2024-01-01

最新评论