自学内容网 自学内容网

@/ConfigurationProperties详解

@ConfigurationProperties 是 Spring 框架中用于将外部配置(如 application.ymlapplication.properties 中的属性)映射到 Java 类中的注解。它能将配置文件中的属性绑定到类的属性上,从而简化配置管理和提高可读性。通常与 @EnableConfigurationProperties@Component 配合使用,用于将配置类注册到 Spring 容器中。

1. 基本用法

假设 application.yml 中有以下内容:

app:
  name: MyApp
  version: 1.0
  author:
    name: John Doe
    email: john.doe@example.com

创建一个 Java 类来接收这些配置:

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

@Component
@ConfigurationProperties(prefix = "app")  // 绑定 `app` 前缀的配置
public class AppProperties {
    private String name;
    private String version;
    private Author author;

    // 内部静态类,用来绑定 `app.author` 下的配置
    public static class Author {
        private String name;
        private String email;

        // Getters and Setters
        public String getName() { return name; }
        public void setName(String name) { this.name = name; }
        public String getEmail() { return email; }
        public void setEmail(String email) { this.email = email; }
    }

    // Getters and Setters
    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; }
    public Author getAuthor() { return author; }
    public void setAuthor(Author author) { this.author = author; }
}

此时,Spring 会将 application.ymlapp 前缀的配置属性自动注入到 AppProperties 对象中。

2. 重要属性与配置

prefix
  • 指定配置文件中的前缀,以区分不同模块的配置。

    @ConfigurationProperties(prefix = "app")
    
ignoreInvalidFields
  • 默认为 false。如果配置文件中有无法转换的字段(如 String 转换为 Integer),将抛出异常。设置为 true 时忽略这些字段。

    @ConfigurationProperties(prefix = "app", ignoreInvalidFields = true)
    
ignoreUnknownFields
  • 默认为 true,表示允许忽略配置文件中多余的字段而不抛出异常。如果设置为 false,则配置文件中存在无法匹配的字段时会抛出异常。

    @ConfigurationProperties(prefix = "app", ignoreUnknownFields = false)
    
ignoreNestedProperties
  • 指定是否忽略嵌套属性。默认 false
exceptionIfInvalid
  • 绑定失败时是否抛出异常。默认 true

3. 使用场景与实践

3.1 使用 @Component 注解

最简单的用法是直接在配置类上加上 @Component 注解,使其成为 Spring 管理的 Bean,然后通过 @Autowired@Resource 来注入。

@Component
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    // 配置字段
}
@Autowired
private AppProperties appProperties;
3.2 配合 @EnableConfigurationProperties 使用

如果不希望在配置类上使用 @Component 注解,可以在 Spring Boot 主类(或任意配置类)中使用 @EnableConfigurationProperties 来激活它:

import org.springframework.boot.context.properties.EnableConfigurationProperties;

@EnableConfigurationProperties(AppProperties.class)
@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}
3.3 配置文件分组(List 与 Map 支持)

对于复杂的配置,可以使用 ListMap 类型。例如:

application.yml

app:
  servers:
    - url: http://server1.com
      timeout: 5000
    - url: http://server2.com
      timeout: 3000

Java 类:

@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private List<Server> servers;

    public static class Server {
        private String url;
        private int timeout;

        // Getters and Setters
    }

    // Getters and Setters
}

此时,app.servers 的配置会自动绑定到 AppProperties 类的 servers 列表中。

4. 校验与默认值

可以使用 JSR-303 校验注解,如 @NotNull, @Min, @Max 等,在配置类中进行属性的校验:

import javax.validation.constraints.NotNull;

@ConfigurationProperties(prefix = "app")
public class AppProperties {
    @NotNull  // 表示 `name` 字段不能为空
    private String name;

    private int version = 1;  // 默认值
}

同时,需要在配置类上加上 @Validated 注解来启用校验功能:

@Validated
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    @NotNull
    private String name;
}

5. 使用 @ConstructorBinding

如果配置类是不可变的(所有属性都是 final),可以使用 @ConstructorBinding 进行绑定。示例如下:

import org.springframework.boot.context.properties.ConstructorBinding;

@ConstructorBinding
@ConfigurationProperties(prefix = "app")
public class AppProperties {
    private final String name;
    private final int version;

    public AppProperties(String name, int version) {
        this.name = name;
        this.version = version;
    }

    public String getName() { return name; }
    public int getVersion() { return version; }
}

6. 区别 @Value@ConfigurationProperties

  • @Value:适合用于简单的属性注入,比如单个属性值的获取。无法处理复杂的嵌套结构和列表映射。

    @Value("${app.name}")
    private String appName;
    
  • @ConfigurationProperties:适合处理复杂的配置结构,支持嵌套对象和集合等类型。

7. 相关依赖与注意事项

  1. @ConfigurationProperties 需要添加 spring-boot-configuration-processor 依赖,以便在编译时生成相关的提示信息(如 IDE 中自动补全):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>
    
  2. 在 Spring Boot 2.2 及更高版本中,@ConfigurationProperties 支持 @ConstructorBinding 进行不可变对象绑定,但需要配合 spring-boot-configuration-processor@EnableConfigurationProperties

8. 总结

@ConfigurationProperties 提供了灵活、易用的方式来将配置文件中的内容映射到 Java 类中。它支持复杂的嵌套结构、列表、Map 类型,并且可以结合 JSR-303 校验注解进行数据验证。适用于处理复杂配置场景,并提高配置管理的安全性和可维护性。


原文地址:https://blog.csdn.net/Gemini1995/article/details/142755972

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!