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

Dan*_*iel 3 configuration spring autowired spring-boot

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

@Validated
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
   ...
}
Run Code Online (Sandbox Code Playgroud)

和这样的配置类:

@Configuration
@EnableScheduling
public class HttpClientConfiguration {

    private final HttpClientProperties httpClientProperties;

    @Autowired
    public HttpClientConfiguration(HttpClientProperties httpClientProperties) {
        this.httpClientProperties = httpClientProperties;
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

在开始我的春季启动应用程序时,我得到了

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.
Run Code Online (Sandbox Code Playgroud)

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

g00*_*00b 13

这是一个有效的用例,但是,HttpClientProperties由于它们未被组件扫描程序扫描,因此您不会被选中.你可以注释您HttpClientProperties@Component:

@Validated
@Component
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

@EnableConfigurationProperties(HttpClientProperties.class) // This is the recommended way
@EnableScheduling
public class HttpClientConfiguration {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

这在Spring引导文档中也有描述.

  • 感谢您的反馈,这是到“当前”的链接,因此措辞可能已更改。重要的信息是“即使前面的配置为AcmeProperties创建了常规bean,我们也建议@ConfigurationProperties仅处理环境,尤其不要从上下文中注入其他bean。” 通过不使用`@ Component`,您可以更清楚地知道该对象是特殊对象,不应注入其他依赖项。这就是@EnableConfigurationProperties(ABC.class)给您的。 (2认同)