Search code examples
springspring-el

spEL in Bean Definition File : How to get a value in an inline list?


Given an inline list from a properties file:

nameList=john,smith,junior

From the bean definition file, I want to always extract the first item in my list. In this case, I would extract 'john'.

Using Spring Framework 3.0.4.RELEASE, my bean property looks as follows:

<property name="mySingleName" value="${nameList}" />

This obviously gives me the whole list.

I attempted to use the following to get the first item in the name list, but was met with an error:

<property name="mySingleName" value="#{${nameList}[0]}" />

The error was:

BeanExpressionException:Exception parsing failed: After parsing a valid expression, there is still more data in the expression:'comma(,)'

I have looked in the Book "Spring In Action", and have looked at the Spring spEL Documentation on Springs website. I have also googled for a quite a bit. Unfortunately, most of the code examples are done in code and not on the spring definition files. Any assistance in this would be greatly appreciated.


Solution

  • In your example you are reading a "nameList" property as a String ( not as a java.util.List ). You would need to convert it to a list first:

    <bean id="listOfNames" class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
        <constructor-arg type="java.lang.String" value="${nameList}"/>
    </bean>
    

    and then you can apply SPeL to it:

    <property name="mySingleName" value="#{listOfNames[0]}" />
    

    similar problem / solution here: Spring: Reading collections form property files