一尘不染

如何将@ConfigurationProperties自动连接到@Configuration?

spring-boot

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

@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应用程序时,

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.

这不是有效的用例,还是我必须以某种方式声明依赖关系?


阅读 321

收藏
2020-05-30

共1个答案

一尘不染

这是一个有效的用例,但是,HttpClientProperties由于组件扫描程序未扫描您的用户,因此未将他们接走。您可以使用来注释您HttpClientProperties@Component

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

这样做的另一种方法(如StephaneNicoll所述是通过@EnableConfigurationProperties()在Spring配置类上使用注释,例如:

@EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way
@EnableScheduling
public class HttpClientConfiguration {
    // ...
}
2020-05-30