如何从Spring Boot应用覆盖依赖库的ConfigurationProperties?
问题解决方案
1. 调整属性类注解,改用自动配置激活
你的DemoProperties类同时标注@Configuration和@ConfigurationProperties会导致依赖库组件扫描逻辑冲突,需调整如下:
- 保留
@Setter、@Getter、@ConfigurationProperties,移除@Configuration - 在依赖库中新增自动配置类,通过
@EnableConfigurationProperties激活属性类
修改后的DemoProperties:
@Setter @Getter @ConfigurationProperties(prefix = "base.props") public class DemoProperties { private String host; private String realm; }
依赖库中的自动配置类(例如DemoAutoConfiguration):
@Configuration @EnableConfigurationProperties(DemoProperties.class) public class DemoAutoConfiguration { // 可在此注入DemoProperties并提供相关服务Bean }
2. 添加配置元数据依赖,解决IDEA提示问题
IntelliJ的"Cannot resolve configuration property"提示是因为缺少配置元数据文件。在依赖库的pom.xml中添加处理器依赖,自动生成元数据:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
打包后Jar包会自动生成META-INF/spring-configuration-metadata.json,IDEA就能识别配置属性。
3. 配置自动配置类扫描路径
Spring Boot应用默认读取依赖库中META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports文件来加载自动配置类。在依赖库的src/main/resources/META-INF/spring/目录下创建该文件,内容为自动配置类的全限定名:
com.sha.demo.DemoAutoConfiguration
这样应用引入依赖后会自动加载配置类,激活DemoProperties。
4. 验证配置是否生效
在Spring Boot应用中注入DemoProperties并测试:
@RestController public class TestController { private final DemoProperties demoProperties; public TestController(DemoProperties demoProperties) { this.demoProperties = demoProperties; } @GetMapping("/test") public String testConfig() { return "Host: " + demoProperties.getHost() + ", Realm: " + demoProperties.getRealm(); } }
启动应用访问/test,若返回配置的Test值,说明配置已生效。
内容的提问来源于stack exchange,提问作者Sha
相关产品推荐
相关产品推荐

