提问者:小点点

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


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

@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启动应用程序时,我得到了

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个答案

匿名用户

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

@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文档中也描述了这一点。

匿名用户

在Spring Boot 2.2.1中,将@ConfigurationProperties tiesScan注释添加到应用程序中。(请注意,这在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>