Monday, May 03, 2010

How to wire a constant in Spring

Spring is a great framework for dependency injection. It helps creating new instances and inject them with references to other objects via constructor arguments or setter methods.

To create a new instance of a class one simply declares a new bean

<bean id="firstDay" class="com.mypackage.Day">
<constructor-arg type="java.lang.Integer" value="1" />

But what if you do not want to create a new instance. Perhaps you already have a class with instances declared as publicly accessible constants (public static) and you just want to access them in the wiring process.

It's easy to get a hold of a constant. Simply use the following

<util:constant id="firstDay" static-field="com.mypackage.Day.MONDAY"/>

For this to work you'll need to include the following

xsi:schemaLocation=" ..."

So there you go, now you have constants wired.

1 comment:

Anonymous said...

In addition, xsi:schemaLocation must contain "". For documentation see

Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.