简体   繁体   中英

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? 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. Is this the only way out to implement this.

Is there a better way to use nested property files in Java?

Create a Car object or something with a model and a year property. 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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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