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?
In addition to being able to reference any particular bean definition as seen above, one @Configuration class may reference the instance of any other @Configuration class using @Autowired . This works because the @Configuration classes themselves are instantiated and managed as individual Spring beans.
In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.
You can use the @EnableConfigurationProperties to link it to the @ConfigurationProperties class and init your data sources accordingly. @Configuration @EnableConfigurationProperties(DataSourcesConfiguration.
Basically, you: use a specific configuration to @EnableConfigurationProperties and @EnableAutoConfiguration , listing all the @ConfigurationProperties files you want to load. in the test class, you load this configuration file of tests, with an initializer class defined by Spring to load application. yml file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With