如何在 Spring Boot 中加载和遍历属性文件

How to load and iterate through properties file in Spring Boot

我有一个 properties 文件,其中的值以逗号分隔。我能够获得 Object 的值,如下所示。谁能告诉我如何分离值并在 String 中获取它。

.properties

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

代码

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

您可以使用带有 @PropertySource@Value 注释来获取 属性 的值。此外,您可以使用 Spring 表达式将其拆分为列表,例如:

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

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

这将为您提供针对 key-1.

配置的所有值的列表

你可以试试下面的方法。

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.
}

.properties

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

代码

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

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

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

或者您可以使用:

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

代码

@Value("#{${keys}}")  private Map<String,String> keys;