Reading a List from properties file and load with spring annotation @Value

前端 未结 16 1568
陌清茗
陌清茗 2020-11-22 14:01

I want to have a list of values in a .properties file, ie:

my.list.of.strings=ABC,CDE,EFG

And to load it in my class directly, ie:

16条回答
  •  长情又很酷
    2020-11-22 14:24

    If you are reading this and you are using Spring Boot, you have 1 more option for this feature

    Usually comma separated list are very clumsy for real world use case (And sometime not even feasible, if you want to use commas in your config):

    email.sendTo=somebody@example.com,somebody2@example.com,somebody3@example.com,.....
    

    With Spring Boot, you can write it like these (Index start at 0):

    email.sendTo[0]=somebody@example.com
    email.sendTo[1]=somebody2@example.com
    email.sendTo[2]=somebody3@example.com
    

    And use it like these:

    @Component
    @ConfigurationProperties("email")
    public class EmailProperties {
    
        private List sendTo;
    
        public List getSendTo() {
            return sendTo;
        }
    
        public void setSendTo(List sendTo) {
            this.sendTo = sendTo;
        }
    
    }
    
    
    @Component
    public class EmailModel {
    
      @Autowired
      private EmailProperties emailProperties;
    
      //Use the sendTo List by 
      //emailProperties.getSendTo()
    
    }
    
    
    
    @Configuration
    public class YourConfiguration {
        @Bean
      public EmailProperties emailProperties(){
            return new EmailProperties();
      }
    
    }
    
    
    #Put this in src/main/resource/META-INF/spring.factories
      org.springframework.boot.autoconfigure.EnableAutoConfiguration=example.compackage.YourConfiguration
    

提交回复
热议问题