Spring XML: Invoking setter methods with multiple arguments

In the JavaBeans idea of a perfect world, every mutable field of an object should be mutated with a single-argument setter method. I find this overly restrictive. At any rate, it is a convention that is not universally followed.

When configuring Java beans with Spring XML files, there isn’t an obvious way to deal with setters that take more than one argument. Consider the following method:

public void setTitles(String... titles)
{
for (String s : titles)
titleSet.add(s);
}

The standard single-arg approach we’re familiar with is:

<bean id="Paul_McCartney" class="com.example.Person">
<propety id="titles" value="Sir"/>
</bean>

But someone with two titles, like “Rev. Dr. Martin Luther King” isn’t easily handled. This is because the XML attribute “value“, like all XML attributes, cannot be multivalued. Here is the workaround:

<bean id="MLK_JR" class="com.example.Person" />

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="targetObject">
        <ref local="MLK_JR"/>
    </property>
    <property name="targetMethod">
        <value>setTitles</value>
    </property>
    <property name="arguments">
        <list>
            <value>"Reverend"</value>
            <value>"Doctor"</value>
        </list>
    </property>
</bean>

Credit for this fix due to this question on StackOverflow.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s