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

查看:261
本文介绍了如何将@ConfigurationProperties自动连接到@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 {
    // ...
}

查看全文

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