如何将@ConfigurationProperties自动连接到@Configuration? [英] How to autowire @ConfigurationProperties into @Configuration?
问题描述
我有一个如下定义的属性类:
I have a properties class defined like this:
@Validated
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
...
}
还有这样的配置类:
@Configuration
@EnableScheduling
public class HttpClientConfiguration {
private final HttpClientProperties httpClientProperties;
@Autowired
public HttpClientConfiguration(HttpClientProperties httpClientProperties) {
this.httpClientProperties = httpClientProperties;
}
...
}
启动Spring Boot应用程序时,我会得到
When starting my spring boot application, I'm getting
Parameter 0 of constructor in x.y.z.config.HttpClientConfiguration required a bean of type 'x.y.z.config.HttpClientProperties' that could not be found.
这不是有效的用例吗,还是我必须以某种方式声明依赖关系?
Is this not a valid use case, or do I have to declare the dependencies some how?
推荐答案
这是一个有效的用例,但是由于组件扫描程序未扫描您的HttpClientProperties
,因此未将它们提取.您可以用@Component
注释HttpClientProperties
:
This is a valid use case, however, your HttpClientProperties
are not picked up because they're not scanned by the component scanner. You could annotate your HttpClientProperties
with @Component
:
@Validated
@Component
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
// ...
}
另一种方式(如 Stephane Nicoll )是通过在Spring配置类上使用@EnableConfigurationProperties()
批注来实现的,例如:
Another way of doing so (as mentioned by Stephane Nicoll) is by using the @EnableConfigurationProperties()
annotation on a Spring configuration class, for example:
@EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way
@EnableScheduling
public class HttpClientConfiguration {
// ...
}