Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 615
Manu Avatar asked Apr 24 '15 14:04

Manu


1 Answers

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.

like image 156
Stephane Nicoll Avatar answered Oct 13 '22 10:10

Stephane Nicoll