简体   繁体   English

如何使用Spring将嵌套键值对从属性文件加载到Java对象中?

[英]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. 我了解在知道所需的属性时如何将Spring与PropertyPlaceholderConfigurer一起使用以加载.properties文件,并使用@Value将这些值存储到变量或某个对象中。

However, how do I have Spring load up a properties file with nested key,value pairs when the keys can vary? 但是,当键可以变化时,我如何让Spring用嵌套的键,值对加载属性文件?

For example, lets say I had the following car.properties file: 例如,假设我有以下car.properties文件:

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,然后是三个嵌套键值对,即一对用于模型,一对用于VIN,以及一对用于车辆类型,即

<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. 我之所以使用这种结构,是因为以后会增加以后的载具,并且我不想更改底层的Java代码。 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? 我将如何使用Spring加载属性文件的每一行作为要存储在arraylist中的车辆值的集合? I'm figuring I'd have a 2D arraylist where each of these vehicles would be an arraylist inside the "all vehicles" arraylist. 我在想我会有一个2D数组列表,其中每个载具都将是“所有载具”数组列表中的一个数组列表。 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. 无论如何,我认为我走在正确的轨道上,但是似乎无法弄清楚如何使用Spring加载嵌套的键值对。 Any suggestions? 有什么建议么?

UPDATED context.xml that works for me: 更新的context.xml对我有用:

Btw, here is the context.xml I'm using: 顺便说一句,这是我正在使用的context.xml:

<?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: 但是,spring可以为您提供一些便利实用程序类:

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

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

}

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

相关问题 如何从SpringBoot中的属性文件加载嵌套键值对 - How to load nested key value pairs from a properties file in SpringBoot Java Properties.load() - 如何切换键值对? - Java Properties.load() - how to switch key value pairs? 如何加载属性文件中的所有键/值对 - How to load all key/value pairs in properties file 如何在Java属性文件中使用逗号分隔键值对 - How to separate key value pairs with comma in Java properties file 如何在春季使用自动装配从属性文件中检索键的值 - How to retrieve the value of a key from properties file in spring using Autowiring 在 Java 中,使用 java.nio 库和 FileChannel,如何从文件加载 Properties 对象? - In Java, using the java.nio library and a FileChannel, how can I load a Properties object from a file? 如何使用Spring注释将Properties文件中的值注入到现有实例(不受Spring管理)的字段中? - How do I inject a value from Properties file to a field of an existing instance (not managed by Spring) using Spring annotations? Java:如何使用Spring注释将.properties文件的内容加载到Properties中? - Java : How to load content of .properties file into Properties using spring annotation? 如何在android中发布文件上传的键/值对 - How do I post key/value pairs with a file upload in android 如何从 java 中的 JSON 文件中删除键值对 - How to remove key value pairs from a JSON file in java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM