在yaml文件配置属性-映射成Java对象

✅ 实现步骤:
在 application.yml 中定义配置。
创建一个 Java Bean 类,用于映射配置。
使用 @ConfigurationProperties 绑定前缀。
在 Spring 配置类或启动类上加上 @EnableConfigurationProperties(Spring Boot 2.4+ 可省略)
示例代码
1️⃣ application.yml

myapp:
  config:
    name: "TestApp"
    version: "1.0.0"
    features:
      enabled: true
      retryLimit: 3

2️⃣ 创建对应的 Java 配置类 MyAppProperties.java

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

@Component
@ConfigurationProperties(prefix = "myapp.config")
public class MyAppProperties {
    private String name;
    private String version;
    private Features features;

    // Getters and Setters

    public static class Features {
        private boolean enabled;
        private int retryLimit;

        // Getters and Setters
    }
}

3️⃣ 使用该配置类的示例:MyService.java

import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final MyAppProperties myAppProperties;

    public MyService(MyAppProperties myAppProperties) {
        this.myAppProperties = myAppProperties;
    }

    public void printConfig() {
        System.out.println("Name: " + myAppProperties.getName());
        System.out.println("Version: " + myAppProperties.getVersion());
        System.out.println("Features Enabled: " + myAppProperties.getFeatures().isEnabled());
        System.out.println("Retry Limit: " + myAppProperties.getFeatures().getRetryLimit());
    }
}

测试输出结果(调用 printConfig())

Name: TestApp
Version: 1.0.0
Features Enabled: true
Retry Limit: 3

你可能感兴趣的:(在yaml文件配置属性-映射成Java对象)