【问题标题】:How to load and iterate through properties file in Spring Boot如何在 Spring Boot 中加载和遍历属性文件
【发布时间】:2019-08-06 08:21:04
【问题描述】:

我有一个properties 文件,其中的值以逗号分隔。我可以得到如下Object 的值。谁能告诉我如何分隔这些值并在字符串中获取它。

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

【问题讨论】:

标签: java spring-boot java-8 properties-file


【解决方案1】:

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

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

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

这将为您提供针对 key-1 配置的所有值的列表。

【讨论】:

  • 有没有办法动态获取值而不是为每个键创建一个变量?
  • 除非您继承PropertyPlaceholderConfigurer,否则不要认为有任何方法可以做到这一点,请阅读此处:stackoverflow.com/a/11416312/1120793
  • 这个答案很好。但是,我接受了维奈的回答,因为它解决了我的问题。也赞成你的答案。谢谢
【解决方案2】:

你可以试试下面的方法。

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

【讨论】:

  • 我更喜欢@Darshan Mehta 的回答。
  • 谢谢。这有帮助。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2014-12-21
    • 2019-03-30
    • 2017-11-17
    • 2015-09-29
    • 2019-02-12
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多