Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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:</p> <ul> <li>You can load the properties file via <a href="http://docs.spring.io/spring/docs/2.0.x/reference/xsd-config.html#xsd-config-body-schemas-util-properties" rel="nofollow"><code>util:properties</code></a> config element</li> <li>You can use <a href="http://docs.spring.io/spring-framework/docs/3.2.x/javadoc-api/org/springframework/beans/BeanWrapperImpl.html" rel="nofollow"><code>BeanWrapperImpl</code></a> to help you set properties on your custom beans.</li> </ul> <p><strong>Example</strong> (might contain typos):</p> <pre><code>&lt;util:properties id="carProperties" location="classpath:car.properties"/&gt; &lt;bean class="my.package.CarLoader"&gt; &lt;property name="sourceProperties" ref="carProperties" /&gt; &lt;/bean&gt; </code></pre> <hr> <pre><code>public class Car { private String name; private String category; // ... Getters and setters } </code></pre> <hr> <pre><code>public class CarLoader { private Properties sourceProperties; public List&lt;Car&gt; getCars() { List&lt;Car&gt; cars = new ArrayList&lt;Car&gt;(); 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; } } </code></pre> <hr> <p><em>UPDATE</em> basic example how to bootstrap application context from <code>main</code> method:</p> <pre><code>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()); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload