@EnableConfigurationProperties 注解功能介绍和完整使用示例

发布时间:2026/6/30 4:59:22

@EnableConfigurationProperties 注解功能介绍和完整使用示例 EnableConfigurationProperties注解功能介绍在 Spring Boot 中EnableConfigurationProperties是用于管理外部配置如application.properties或application.yml的核心注解之一。它的主要功能包括启用配置属性绑定功能它告诉 Spring Boot 去注册带有ConfigurationProperties注解的类。如果没有该注解即使配置类上有ConfigurationPropertiesSpring 也不会自动将其创建为 Bean。自动注册 Bean将指定的配置属性类自动注册为 Spring 上下文中的 Bean使其可以在应用的其他位置被注入和使用。支持批量注册可以在该注解中传入多个配置类一次性启用并注册多个配置属性 Bean。简单来说ConfigurationProperties负责定义“如何将配置文件中的属性绑定到 Java 对象”而EnableConfigurationProperties则负责“激活这个绑定过程并将对象注册为 Spring Bean”。完整使用示例以下是一个将配置文件属性绑定到 Java 对象并注入使用的完整流程第一步定义配置属性类创建一个普通的 Java 类POJO使用ConfigurationProperties指定配置前缀并提供对应的字段和 setter 方法importorg.springframework.boot.context.properties.ConfigurationProperties;importlombok.Data;DataConfigurationProperties(prefixtest.app)publicclassAppProperties{privateStringname;privateinttimeout;}第二步启用配置属性绑定在主启动类或任意配置类上添加EnableConfigurationProperties注解并指定刚才定义的配置类importorg.springframework.boot.SpringApplication;importorg.springframework.boot.autoconfigure.SpringBootApplication;importorg.springframework.boot.context.properties.EnableConfigurationProperties;SpringBootApplicationEnableConfigurationProperties(AppProperties.class)// 启用配置属性绑定publicclassApplication{publicstaticvoidmain(String[]args){SpringApplication.run(Application.class,args);}}第三步在配置文件中设置属性在application.properties或application.yml中添加对应的配置项支持松散绑定如驼峰与下划线自动转换test.app.namedemoName test.app.timeout1000第四步在业务代码中注入使用配置类被注册为 Bean 后可以直接在 Service 或 Controller 中通过依赖注入使用importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;ServicepublicclassMyService{AutowiredprivateAppPropertiesappProps;publicvoidprintConfig(){System.out.println(Name: appProps.getName());System.out.println(Timeout: appProps.getTimeout());}} 补充说明与最佳实践替代方案如果你的配置类本身已经加了Component注解Spring Boot 会通过组件扫描自动将其注册为 Bean此时可以省略EnableConfigurationProperties。但官方更推荐**不在配置类上加 ****Component**而是通过EnableConfigurationProperties显式注册这样语义更清晰也更利于模块化设计。批量注册如果有多个配置类可以这样写EnableConfigurationProperties({AppProperties.class, DatabaseConfig.class})。IDE 提示支持建议在pom.xml中引入spring-boot-configuration-processor依赖这样在编写配置文件时IDE 会自动提供属性名补全和校验提示。

相关新闻