How to load and iterate through properties file in Spring Boot

问题: I've a properties file in which the values are comma separated. I'm able to get the values as Object as below. Could anyone please tell me how to separate the values and ge...

问题:

I've a properties file in which the values are comma separated. I'm able to get the values as Object as below. Could anyone please tell me how to separate the values and get it in String.

.properties

key-1 = value1,value11
key-2 = value2,value22
key-3 = value3,value33
key-4 = value4,value44

Code

@PropertySource( value = "classpath:test1.properties", name = "test1" )

AbstractEnvironment ae = (AbstractEnvironment)env;
org.springframework.core.env.PropertySource test1Source = 
ae.getPropertySources().get("test1");
Properties propsTest1 = (Properties)test1Source.getSource();

   for(Object key : propsTest1.keySet()){
   System.out.println("Properties file======>   propsTest1.get(key));
  }

回答1:

You can try something like below.

Properties propsTest1 = (Properties)test1Source.getSource();

for(Map.Entry<Object, Object> e : propsTest1.entrySet()){

   String value = (String)e.getValue();
   String[] values = value.split(",");
   // If you have spaces as between values, you have to take care of it.
}

回答2:

You can use @Value annotation with @PropertySource to get the value of a property. Also, you can use Spring Expression to split it into list, e.g.:

@PropertySource( value = "classpath:test1.properties", name = "test1" )
public class PropertyClass {

    @Value("#{'${key-1}'.split(',')}") 
    private List<String> key1Values;
}

This would give you the list of all the values configured against key-1.


回答3:

.properties

map.key[0] = value1,value11
map.key[1] = value2,value22
map.key[2] = value3,value33
map.key[3] = value4,value44

Code

@ConfigurationProperties(prefix="map")
public class YourConfig {

    private List<String> keys = new ArrayList<String>();

    public List<String> getKeys() {
        return this.servers;
    }
}

Or you can use:

keys={key-1:'value1',key-1:'value2',....}

Code

@Value("#{${keys}}")  private Map<String,String> keys;
  • 发表于 2019-03-17 04:40
  • 阅读 ( 171 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除