如何使用Spring将嵌套键值对从属性文件加载到Java对象中? [英] How do I load nested key value pairs from a properties file into a Java object using Spring?

查看:197
本文介绍了如何使用Spring将嵌套键值对从属性文件加载到Java对象中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解当我们知道要使用的属性时,如何将Spring与PropertyPlaceholderConfigurer一起使用以加载.properties文件,并使用@Value将这些值存储到变量或某个对象中.

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.

但是,当键可以变化时,我如何让Spring用嵌套的键,值对加载属性文件?

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

例如,假设我有以下car.properties文件:

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

其中,属性文件的每一行都有一个make键,然后是三个嵌套键值对,即,一个用于模型,一个用于VIN,以及一个用于车辆类型,即

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

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

我正在使用此结构,因为以后会增加以后的载具,并且我不想更改我的基础Java代码.假设我要使用这些车辆属性来生成一些有关车辆的随机数据以进行测试.

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.

我将如何使用Spring加载属性文件的每一行作为要存储在arraylist中的车辆值的集合?我在想我会有一个2D数组列表,其中每个载具都将是所有载具"数组列表中的一个数组列表.然后,我将随机选择一个车辆数组列表以生成虚拟车辆数据.

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.

无论如何,我认为我走在正确的轨道上,但是似乎无法弄清楚如何使用Spring加载嵌套的键值对.有什么建议吗?

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?

对我有用的更新后的context.xml:

UPDATED context.xml that works for me:

顺便说一句,这是我正在使用的context.xml:

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>

推荐答案

spring不可能为您做到这一点.您将需要自己实现解析.但是,spring可以为您提供一些便利实用程序类:

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:

示例(可能包含错字):

<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 基本示例如何从main方法引导应用程序上下文:


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());
        }
    }

}

这篇关于如何使用Spring将嵌套键值对从属性文件加载到Java对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆