Reputation: 225
I was trying out the new Spring Boot 2.2.0.RC1 release, in particular the new configuration properties constructor binding feature described in section 2.8.2. Constructor binding. I set up a very small project with a class like so:
@Configuration
@ConfigurationProperties("acme")
public class AppConfig {
private final String stuff;
public AppConfig(String stuff) {
this.stuff = stuff;
}
public String getStuff() {
return stuff;
}
}
and an application.yml like this:
server:
port: 9000
acme:
stuff: hello there
My main method is in this class:
@SpringBootApplication
public class AcmeApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(AcmeApplication.class)
.logStartupInfo(true)
.bannerMode(Banner.Mode.CONSOLE)
.web(WebApplicationType.SERVLET)
.run();
}
}
The result of running the application is this output:
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.acme.config.AppConfig required a bean of type 'java.lang.String
' that could not be found.
Action:
Consider defining a bean of type 'java.lang.String' in your configuration.
Interestingly, if I change the code in the AppConfig class to use properties binding, by removing the constructor, removing the "final" modifier from the "stuff" field and adding a setStuff(String) method, the application starts fine (the setStuff method is called as expected).
What am I missing in trying to get the constructor binding to work? I've tried removing the @Configuration annotation, adding the @EnableConfigurationProperties annotation, adding @ConfigurationPropertiesScan and so forth, but from reading the documentation, none of those things seem to be applicable here anyway. It seems to me it is trying to inject Spring beans rather than build and inject configuration property objects. That is why I thought that maybe removing the @Configuration annotation would help, but it made no difference. By the way, I would like this AppConfig to be a Spring Bean so I can inject it into Service classes, for example.
Upvotes: 3
Views: 12353
Reputation: 225
I was looking at the milestone documentation by mistake. The updated RC1 documentation shows that I need to use the @ImmutableConfigurationProperties annotation as well as the @ConfigurationPropertiesScan annotation.
Also see: https://github.com/spring-projects/spring-boot/issues/18543
Upvotes: 2
Reputation: 11
Performed a brief research. Here seems to be the reason https://github.com/spring-projects/spring-boot/issues/16928#issuecomment-494717209 Please review the whole thread to get more context. And here is the issue description mentioned previously https://github.com/spring-projects/spring-boot/issues/8762#issuecomment-494310988
Upvotes: 1