如何配置自定义源以提供 Spring Boot 的 @ConfigurationProperties [英] How to configure a custom source to feed Spring Boot's @ConfigurationProperties
问题描述
我是 Spring Boot 的新手,正在阅读有关 @ConfigurationProperties 注释如何在没有 @Value 注释的情况下自动注入字段值的信息.
I'm new to Spring Boot and reading about how @ConfigurationProperties annotation enables auto-injection of field values without @Value annotation.
@Configuration
@ConfigurationProperties(locations = "classpath:some.properties", prefix = "something")
public class MyConfiguration { .. }
我想使用 Groovy 的 ConfigSlurper
来读取我的属性配置.有没有办法将 @ConfigurationProperties
与自定义属性读取器相关联,可能是处理 ConfigSlurper
的 Spring 类的自定义扩展?或者有没有办法用不同的功能模拟相同的行为?
I'd like to use Groovy's ConfigSlurper
to read my property configuration. Is there a way to associate @ConfigurationProperties
with a custom property reader, may be a custom extension of Spring class that deals with ConfigSlurper
? Or is there a way to simulate the same behavior with a different feature?
推荐答案
这不是 @ConfigurationProperties
的目的.@ConfigurationProperties
绑定 Environment
中可用的任何内容.locations
属性在 1.4 中已弃用,并将在未来版本中删除.
That's not what @ConfigurationProperties
is meant to do. @ConfigurationProperties
binds whatever is available from the Environment
. The locations
attribute is deprecated in 1.4 and will be removed in a future release.
这个想法是你指定一个前缀,如果它们是环境中匹配该前缀的键,我们会在你的 POJO 中注入相关属性.如果你想通过这种机制使用该基础设施,请删除 locations
注释上的属性并使用您自己的属性源更新环境.另一个答案为您提供了一种方法,您可以使用 EnvironmentPostProcessor
将您的实现挂钩到环境中.
The idea is that you specify a prefix and if they are keys matching that prefix in the environment, we inject the relevant properties in your POJO.If you want to use that infrastructure with this mechanism, please remove the locations
attribute on the annotation and update the environment with your own property source. The other answer gives you a way to do that and you can use an EnvironmentPostProcessor
to hook your implementation to the environment.
这篇关于如何配置自定义源以提供 Spring Boot 的 @ConfigurationProperties的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!