I want to bind my application.properties into a class automatically by using @ConfigurationProperties annotation. First, I tried with @Value annotation and was able to inject pr
The main problem is that you do not have setters. When you put setters to ConfigBuilder works fine. The ConfigBuilder must be like this
@Component
@ConfigurationProperties(prefix="my")
public class ConfigBinder {
private String name;
private String url;
// Getters and Setters !!!
}
You need to remove @Component from you properties class and add setters because standard bean property binding is used by @ConfigurationProperties
:
@ConfigurationProperties(prefix="my")
public class ConfigBinder {
private String name;
private String url; // expected to be filled automatically
public String getUrl() {
return this.url;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public void setUrl(String url) {
this.url = url;
}
}
And add @EnableConfigurationProperties to your main class:
@SpringBootApplication
@EnableConfigurationProperties(ConfigBinder.class)
public class Application {
public static void main(String[] args) {
final ApplicationContext ctx = SpringApplication.run(Application.class, args);
final ConfigBinder confs = ctx.getBean(ConfigBinder.class);
System.out.println(confs.getUrl());
System.out.println(confs.getName());
}
}