【问题标题】:how to read from property file in spring boot如何在spring boot中从属性文件中读取
【发布时间】:2019-01-11 07:28:15
【问题描述】:

我能够从我的 Spring Boot 应用程序中的属性文件中读取('fruits' 的值),成功地使用@Value 如下。

@Value("${fruits}")
private String[] fruitarray;

从下面

文件:applicon.properties

#section_1
fruits=apple,mango,banana
#section_2
apple.native=aaaa
apple.cost=100
apple.name=xxyyzz

现在,我想知道,如何从属性文件的 section_2 动态访问键值。 我的意思是,......在我们上面的代码中,我们已经得到了水果数组,并使用@Value 将其设置为“fruitarray”。现在我将如何通过在 java/spring-boot 方式中使用 fruitarray[0] 变量来访问“apple.native”的值?

谢谢

【问题讨论】:

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


【解决方案1】:

您也可以通过以下方式定义属性文件

key.0=value0
key.1=value1

/** 从属性文件返回数组。数组必须定义为 "key.0=value0", "key.1=value1", ... */ public List getSystemStringProperties(String key) {

// result list
List<String> result = new LinkedList<>();

// defining variable for assignment in loop condition part
String value;

// next value loading defined in condition part
for(int i = 0; (value = YOUR_PROPERTY_OBJECT.getProperty(key + "." + i)) != null; i++) {
    result.add(value);
}

// return
return result;

}

【讨论】:

    【解决方案2】:

    您可以尝试将所有属性作为 Bean 获取,并在遍历水果列表时动态访问您的属性:

    @Autowired
    private Environment env;
    ...
    env.getProperty(fruits[i] + ".native");
    ...
    

    来源:http://www.baeldung.com/properties-with-spring#usage

    【讨论】:

    • spring boot 默认提供 application.properties 注入,因此无需全部执行。
    【解决方案3】:

    就这么简单:

        @Value("${apple.native}")
        private String Native;
    
        @Value("${apple.cost}")
        private Double cost;
    
        @Value("${apple.name}")
        private String name;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-27
      • 2016-04-29
      • 1970-01-01
      • 2018-09-28
      • 2018-10-16
      • 2019-07-23
      • 2018-10-27
      • 2020-07-01
      相关资源
      最近更新 更多