Spring Boot: read list from yaml using @Value or @ConfigurationProperties

后端 未结 4 819
旧时难觅i
旧时难觅i 2020-12-28 08:25

I want to read a list of hosts from a yaml file (application.yml), the file looks like this:

cors:
    hosts:
        allow: 
            - http://foo1/
             


        
相关标签:
4条回答
  • 2020-12-28 08:33

    It's easy, the answer is in this doc and also in this one

    So, you have a yaml like this:

    cors:
        hosts:
            allow: 
                - http://foo1/
                - http://foo2/
                - http://foo3/
    

    Then you first bind the data

    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.stereotype.Component;
    
    import java.util.List;
    
    @Component
    @ConfigurationProperties(prefix="cors.hosts")
    public class AllowedHosts {
        private List<String> HostNames; //You can also bind more type-safe objects
    }
    

    Then in another component you just do

    @Autowired
    private AllowedHosts allowedHosts;
    

    And you are done!

    0 讨论(0)
  • 2020-12-28 08:33

    I met the same problem, But solved, give you my solution

    exclude-url: >
      /management/logout,
      /management/user/login,
      /partner/logout,
      /partner/user/login
    

    success in the version of Spring boot 2.1.6.RELEASE

    0 讨论(0)
  • 2020-12-28 08:47

    I have been able to read list from properties like below way-

    Properties-

    cors.hosts.allow[0]=host-0
    cors.hosts.allow[1]=host-1
    

    Read property-

    @ConfigurationProperties("cors.hosts")
    public class ReadProperties {
        private List<String> allow;
    
        public List<String> getAllow() {
           return allow;
        }
        public void setAllow(List<String> allow) {
            this.allow = allow;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 08:53

    use comma separated values in application.yml

    corsHostsAllow: http://foo1/, http://foo2/, http://foo3/
    

    java code for access

    @Value("${corsHostsAllow}")    
    String[] corsHostsAllow
    

    I tried and succeeded ;)

    0 讨论(0)
提交回复
热议问题