spring boot 加载配置文件

在 Spring Boot 中,加载配置文件的常见方法包括使用 @PostConstructApplicationListener 和 @ConfigurationProperties。以下是它们的详细介绍、示例代码及适用场景:

1. 使用 @PostConstruct

作用:在 Bean 初始化完成后执行自定义逻辑,适合在依赖注入后立即加载配置。
实现方式:结合 @Value 或 Environment 对象读取配置。

示例代码:

import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyConfigLoader {

    @Value("${app.name}")
    private String appName;

    private final Environment env;

    public MyConfigLoader(Environment env) {
        this.env = env;
    }

    @PostConstruct
    public void init() {
        String appVersion = env.getProperty("app.version");
        System.out.println("App Name: " + appName);
        System.out.println("App Version: " + appVersion);
    }
}

注意事项

  • 确保依赖的 Bean 已初始化。

  • 避免在 @PostConstruct 中执行耗时操作,可能延迟应用启动。

2. 使用 ApplicationListener

作用:监听 Spring 应用事件(如 ApplicationReadyEvent),在应用完全启动后加载配置。
实现方式:实现 ApplicationListener 接口,监听特定事件。

示例代码:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyAppListener implements ApplicationListener<ApplicationReadyEvent> {

    private final Environment env;

    public MyAppListener(Environment env) {
        this.env = env;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        String dbUrl = env.getProperty("database.url");
        System.out.println("Database URL: " + dbUrl);
    }
}

适用场景

  • 需要在所有 Bean 初始化完成后执行逻辑。

  • 执行启动后的检查或初始化任务。

事件类型

  • ApplicationReadyEvent:应用已完全启动。

  • ApplicationStartedEvent:应用启动后,但尚未完全初始化。

  • 3. 使用 @ConfigurationProperties

    作用:将配置文件中的属性绑定到 Java 对象,提供结构化配置管理。
    实现方式:定义配置类并使用 @ConfigurationProperties 注解。

    示例代码:
  • 定义配置类

  • import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;

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

        // Getter 和 Setter 必须存在!
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getVersion() { return version; }
        public void setVersion(String version) { this.version = version; }
    }

  • 注入配置类

  • import org.springframework.stereotype.Service;

    @Service
    public class MyService {
        private final AppConfig appConfig;

        public MyService(AppConfig appConfig) {
            this.appConfig = appConfig;
        }

        public void printConfig() {
            System.out.println("App Name: " + appConfig.getName());
            System.out.println("App Version: " + appConfig.getVersion());
        }
    }

配置文件(application.yml

app:
  name: MyApp
  version: 1.0.0

优点

  • 类型安全,避免硬编码字符串。

  • 支持嵌套属性、验证(如 @Validated)和默认值。

对比总结

方法适用场景优点缺点
@PostConstructBean 初始化后立即执行简单配置加载简单直接,无需额外配置不适用于复杂逻辑或依赖未就绪的情况
ApplicationListener应用启动后执行复杂初始化逻辑确保所有 Bean 就绪,安全可靠代码稍显复杂
@ConfigurationProperties结构化配置管理类型安全,支持复杂配置需要定义配置类和 Getter/Setter

其他方法补充:直接使用 Environment

如果用户提到的 getConfig 是指直接通过 Environment 对象获取配置,示例代码如下:

java

复制

import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    private final Environment env;

    public MyComponent(Environment env) {
        this.env = env;
    }

    public void printConfig() {
        String value = env.getProperty("key");
        System.out.println("Value: " + value);
    }
}

特点:灵活但缺乏结构化,适合零散配置项。

根据需求选择最合适的方法,通常推荐 @ConfigurationProperties 管理复杂配置,@PostConstruct 处理简单初始化,ApplicationListener 用于启动后任务。

### 如何在Spring Boot加载并使用 `demo.properties` 配置文件 #### 1. 创建自定义配置文件Spring Boot项目中,默认支持两种类型的配置文件:`application.properties` 和 `application.yml`。然而,如果需要创建一个名为 `demo.properties` 的自定义配置文件,则需手动实现其加载逻辑。 首先,在项目的资源目录下(通常是 `src/main/resources/`),新建一个名为 `demo.properties` 的文件,并为其添加一些键值对作为示例: ```properties myapp.name=Demo Application myapp.age=5 ``` 此操作基于引用说明[^1]。 --- #### 2. 编写Java类绑定属性 为了使上述配置能够被程序读取,可以利用 Spring 提供的 `@ConfigurationProperties` 注解将这些属性映射到 Java 类中。以下是具体实现方式: ```java import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @Component @ConfigurationProperties(prefix = "myapp") public class DemoProperties { private String name; private int age; // Getters and Setters public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` 这段代码展示了如何通过 `@ConfigurationProperties` 将 `demo.properties` 文件中的数据注入到 Java Bean 中[^4]。 --- #### 3. 启用配置属性扫描 为了让 Spring 能够识别并处理带有 `@ConfigurationProperties` 注解的类,还需要启用相应的功能。可以通过以下方法之一完成: - **全局启用** 在主应用程序启动类上添加 `@EnableConfigurationProperties` 注解,并指定要使用的配置类: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties(DemoProperties.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } ``` - 或者直接依赖于自动装配机制,无需额外声明即可生效[^3]。 --- #### 4. 测试配置文件加载效果 最后一步是在控制器或其他组件中测试该配置是否成功加载。例如,编写一个简单的 REST 控制器来展示配置项的内容: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DemoController { @Autowired private DemoProperties demoProperties; @GetMapping("/config") public String getConfig() { return "Name: " + demoProperties.getName() + ", Age: " + demoProperties.getAge(); } } ``` 当访问 `/config` 接口时,应该返回类似于 `"Name: Demo Application, Age: 5"` 的响应结果[^5]。 --- ### 总结 以上过程涵盖了从创建自定义配置文件到将其集成至 Spring Boot 应用程序的具体步骤。值得注意的是,虽然本文以 `.properties` 格式的文件为例进行了讲解,但在实际开发过程中也可以选择 YAML 格式替代之[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值