Wednesday, September 23, 2009

Spring Bean Constructor Args

Spring bean configurations frequently contain beans to which you pass constructor arguments. When setting constructor args, you can either reference them by index or by type. This example shows referencing by index.

<bean id="MyBean" class="com.mycompany.MyClass">
<constructor-arg index="0" ref="SomeOtherBean">
<constructor-arg index="1" ref="SomeOtherBean2">
<bean>


In this example, the spring configuration will break if the order of the constructor arguments change. A more robust way to wire this is to set the constructors by type.

<bean id="MyBean" class="com.mycompany.MyClass">
<constructor-arg type="com.mycompany.MyClass1"
ref="SomeOtherBean">
<constructor-arg type="com.mycompany.MyClass2"
ref="SomeOtherBean2">
<bean>


Now if the order of the constructor arguments change, the bean configuration does not need to change.

It's not always possible to do this, particularly if you have multiple constructor arguments of the same type (although you can mix and match by index and by type), but I recommend referencing by type whenever possible.

No comments:

Post a Comment