问题
I have a properties class defined like this:
@Validated
@ConfigurationProperties(prefix = "plugin.httpclient")
public class HttpClientProperties {
...
}
And a configuration class like this:
@Configuration
@EnableScheduling
public class HttpClientConfiguration {
private final HttpClientProperties httpClientProperties;
@Autowired
public HttpClientConfiguration(HttpClientProperties httpClientProperties) {
this.httpClientProperties = httpClientProperties;
}
...
}
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?
回答1:
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 {
// ...
}
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 {
// ...
}
This is also described in the Spring boot docs.
来源:https://stackoverflow.com/questions/43797924/how-to-autowire-configurationproperties-into-configuration