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

会有一股神秘感。 提交于 2019-11-30 04:59:47

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!

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 ;)

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!