简体   繁体   中英

How do I load nested key value pairs from a properties file into a Java object using Spring?

I understand how to use Spring with the PropertyPlaceholderConfigurer to load a .properties file when we know what properties to expect, and use @Value to store those values into variables or some object.

However, how do I have Spring load up a properties file with nested key,value pairs when the keys can vary?

For example, lets say I had the following car.properties file:

Chevy=Corvette:String,1234567890:long,sportsCar:String
Honda=Odyssey:String,2345678910:long,minivan:String
Ford=F350:String,4567891011:long,truck:String

where each line of the properties file has a key which is the make, followed by three nested key,value pairs ie, one for the model, one for the VIN, and one for the vehicle type ie,

<make>=<model>:<dataType>,<vin>:<dataType>,<vehicleType>:<dataType>

I'm using this structure since future vehicles will be added later, and I don't want to change my underlying Java code. And let's say I want to use these vehicle properties to generate some random data about vehicles for testing.

How would I use Spring to load each line of the properties file as a collection of vehicle values to be stored in an arraylist? I'm figuring I'd have a 2D arraylist where each of these vehicles would be an arraylist inside the "all vehicles" arraylist. Then I would randomly select one of the vehicle arraylists to generate dummy vehicle data.

Anyway, I think I'm on the right track, but just can't seem to figure out how I would load my nested key,value pairs using Spring. Any suggestions?

UPDATED context.xml that works for me:

Btw, here is the context.xml I'm using:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
       http://www.springframework.org/schema/util     http://www.springframework.org/schema/util/spring-util-2.0.xsd">

    <!-- creates a java.util.Properties instance with values loaded from the supplied     location -->
<util:properties id="carProperties" location="classpath:/car.properties"/>

    <bean class="com.data.rcgen.generator.CarLoader">
        <property name="sourceProperties" ref="carProperties" />
    </bean>

</beans>

There is no way spring will do this one for you. You will need to implement the parsing yourself. However, spring can provide some convenience utility classes for you:

Example (might contain typos):

<util:properties id="carProperties" location="classpath:car.properties"/>

<bean class="my.package.CarLoader">
    <property name="sourceProperties" ref="carProperties" />
</bean>

public class Car {
    private String name;
    private String category;
    // ... Getters and setters
}

public class CarLoader {

    private Properties sourceProperties;

    public List<Car> getCars() {
        List<Car> cars = new ArrayList<Car>();
        for (Object key : sourceProperties.keySet()) {
            // Do the parsing - naive approach
            String[] values = sourceProperties.getProperty((String) key).split(",");
            // Create bean wrapper and set the parsed properties... will handle data convesions with 
            // default property editors or can use custom ConversionService via BeanWrapper#setConversionService
            BeanWrapper wrappedCar = PropertyAccessorFactory.forBeanPropertyAccess(new Car());
            wrappedCar.setPropertyValue("name", values[0].split(":")[0]); // Getting rid of the `:type`
            wrappedCar.setPropertyValue("category", values[2].split(":")[0]); // Getting rid of the `:type`
            // Phase 3 - prosper
            cars.add((Car) wrappedCar.getWrappedInstance());
        }
        return cars;
    }

    public void setSourceProperties(Properties properties) {
        this.sourceProperties = properties;
    }

}

UPDATE basic example how to bootstrap application context from main method:

public class Main {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("context.xml");
        CarLoader carLoader = context.getBean(CarLoader.class);
        for (Car car : carLoader.getCars()) {
            System.out.println("CAR - " + car.getName());
        }
    }

}

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