ConfigurationProperties does not bind properties

后端 未结 2 887
醉梦人生
醉梦人生 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: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());
        }
    
    }
    

提交回复
热议问题