如何将@ConfigurationProperties 自动连接到@Configuration? [英] How to autowire @ConfigurationProperties into @Configuration?

查看:38
本文介绍了如何将@ConfigurationProperties 自动连接到@Configuration?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的属性类:

I have a properties class defined like this:

@Validated
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
   ...
}

还有一个这样的配置类:

And a configuration class like this:

@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 {
    // ...
}

这也在 Spring 启动文档.

这篇关于如何将@ConfigurationProperties 自动连接到@Configuration?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆