如何将@ConfigurationProperties自动装配到@Configuration中?

时间:2017-05-05 06:25:59

标签: spring spring-boot configuration autowired

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

@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;
    }

    ...
}

启动我的春季启动应用程序时,我正在

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.

这不是一个有效的用例,还是我必须如何声明依赖关系?

2 个答案:

答案 0 :(得分:11)

这是一个有效的用例,但是,HttpClientProperties未被拾取,因为它们未被组件扫描程序扫描。您可以使用HttpClientProperties注释@Component

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

另一种方法(如Stephane Nicoll所述)是在Spring配置类上使用@EnableConfigurationProperties()注释,例如:

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

Spring boot docs中也对此进行了描述。

答案 1 :(得分:0)

在 Spring Boot 2.2.1+ 中,向应用程序添加 @ConfigurationPropertiesScan 注释。 (请注意,这在 2.2.0 版中默认启用。)这将允许在不使用 @ConfigurationProperties@EnableConfigurationProperties 的情况下选取所有用 @Component 注释的类。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

此外,要为用 @ConfigurationProperties 注释的类生成元数据,IDE 使用它在 application.properties 中提供自动完成和文档,请记住添加以下依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>