ConfigurationProperties does not bind properties

后端 未结 2 895
醉梦人生
醉梦人生 2021-02-19 02:22

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

相关标签:
2条回答
  • 2021-02-19 03:11

    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 !!!
    }
    
    0 讨论(0)
  • 2021-02-19 03:13

    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());
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题