简体   繁体   English

如何从SpringBoot中的属性文件加载嵌套键值对

[英]How to load nested key value pairs from a properties file in SpringBoot

Is there a better manner to implement properties file having key-value pairs as value using Spring/Spring Boot? 是否有更好的方法使用Spring / Spring Boot实现将键值对作为值的属性文件? I want to create a property file where the key contains a couple of key-value pair as value. 我想创建一个属性文件,其中的键包含一对键值对作为值。

I tried below implementation:- 我尝试了以下实现:-

Properties file:- 属性文件:

Fiat=model:pet,year:1996
Honda=model:dis,year:2000

And i have below class trying to read the properties file. 我有下面的类试图读取属性文件。

@Component
@PropertySources(@PropertySource("classpath:sample.properties"))
public class PropertiesExtractor {

    @Autowired
    private Environment env;

    public String pullValue(String node) {

    String value = env.getProperty(node);
    System.out.println(value);//for Fiat, i get syso as **model:pet,year:1996**
}

} }

I need to parse the values using java, to get the individual value. 我需要使用java解析值,以获得单个值。 Is this the only way out to implement this. 这是实现此目标的唯一出路。

Is there a better way to use nested property files in Java? 有没有更好的方法在Java中使用嵌套属性文件?

Create a Car object or something with a model and a year property. 使用modelyear属性创建Car对象或其他东西。 Then create something like this 然后创建这样的东西

@ConfigurationProperties("foo")
public class CarProperties {

    private Map<String,Car> cars;

    // Getters/Setters
}

Add add @EnableConfigurationProperties(CarProperties.class) in your main configuration class. 在主配置类中添加添加@EnableConfigurationProperties(CarProperties.class)

Then you can inject that config as follows: 然后,您可以按如下方式注入该配置:

foo.cars.Fiat.model=pet
foo.cars.Fiat.year=1996
foo.cars.Honda.model=dis
foo.cars.Honda.year=2000

There is more info in the doc. 在文档中有更多信息。

You can use yaml files with spring as well: 您还可以将yaml文件与spring一起使用:

http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-yaml http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-yaml

This way, you can work with 这样,您可以与

Fiat:
  model: pet
  year: 1996
Honda:
  model: dis
  year: 2000

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM