Spring Boot 动态加载本地配置文件

Spring Boot 是一个基于 Spring 框架的项目,它简化了基于 Spring 的应用开发。在实际开发中,我们经常需要根据不同的环境(开发、测试、生产等)来加载不同的配置文件。Spring Boot 支持动态加载本地配置文件,这使得我们可以在不重启应用的情况下,动态地切换配置。

1. 动态加载配置文件的原理

Spring Boot 通过 Environment 抽象来获取当前环境的属性。Environment 抽象中有一个 getPropertySources() 方法,该方法返回一个 PropertySource 列表,每个 PropertySource 代表一个配置源。Spring Boot 会按照 PropertySource 的顺序来加载配置属性。

2. 配置文件的命名规则

Spring Boot 默认会加载 application.propertiesapplication.yml 文件。如果需要根据不同的环境加载不同的配置文件,可以按照以下命名规则:

  • application-{profile}.propertiesapplication-{profile}.yml:加载指定 profile 的配置文件。
  • application.propertiesapplication.yml:加载默认的全局配置文件。

3. 动态加载配置文件的实现

3.1 创建配置文件

首先,创建两个配置文件:application-dev.propertiesapplication-prod.properties,分别用于开发环境和生产环境。

# application-dev.properties
app.name=MyApp Dev

# application-prod.properties
app.name=MyApp Prod

3.2 配置 application.properties

application.properties 文件中,指定默认的 profile。

spring.profiles.active=dev

3.3 编写配置加载类

创建一个配置加载类,用于动态切换 profile。

@Configuration
@ConfigurationProperties(prefix = "app")
public class AppConfig {
    private String name;

    // getter and setter
}

3.4 动态切换 profile

在需要动态切换配置时,可以通过修改 application.properties 文件中的 spring.profiles.active 属性来实现。

4. 类图

classDiagram
    class Environment {
        +getPropertySources() : List<PropertySource>
    }
    class PropertySource {
        +getName() : String
        +getProperty(String) : String
    }
    class AppConfig {
        -spring.profiles.active : String
        +name : String
    }
    Environment --> PropertySource: contains

5. 饼状图

假设我们有三个 profile:dev、test 和 prod,它们的比例分别为 60%、20% 和 20%。

pie
    "dev" : 60
    "test" : 20
    "prod" : 20

6. 结语

通过本文的介绍,我们了解到了 Spring Boot 动态加载本地配置文件的原理和实现方法。动态加载配置文件可以让我们根据不同的环境来加载不同的配置,提高了应用的灵活性和可维护性。同时,我们也学习了如何通过修改 application.properties 文件中的 spring.profiles.active 属性来动态切换 profile。希望本文对您有所帮助。

注意:本文中的代码示例仅供参考,实际开发中可能需要根据具体需求进行调整。