Saturday, November 24, 2007

More ColdSpring updates!

One thing I love about Spring is every once in a while you wish you had some special type of bean only to find that Spring already has it. Collection factory beans are some of these types of objects, which I actually use quite a bit at work. Let's say you have configured a component you use across many of your applications, so you put its configuration in a base file and include it in each application with ColdSpring's <include> tag. This is a great approach for reusability, but if you want to use arrays or structs to define application specific parameters to that component you're stuck. A lot of times we end up creating special 'config beans' so we can use the ref tag, but many times these are just wrappers over structs anyway. Why use that type of component at all, if you could just define a struct in your config file and reference it wherever you need it? Well, that's the point of the collection factories. Here's an example of these two new components at work:

First I have a ListFactoryBean instance, which you need to remember from spring semantics will return an Array.

<bean id="list.factory" class="coldspring.beans.factory.config.ListFactoryBean">
    <property name="sourceList">

And now here's a MapFactoryBean, which will return a Struct:

<bean id="map.factory" class="coldspring.beans.factory.config.MapFactoryBean">
    <property name="sourceMap">
            <entry key="one">&tl;value>hello&tl;/value>
            <entry key="one"><value>world</value>

Now I can use the ref tag for these maps and lists instead of directly defining them.

<bean id="testBean" class="coldspring.tests.testBean" lazy-init="false">
    <property name="myList">
        <ref bean="list.factory"/>
    <property name="myMap">
        <ref bean="map.factory"/>

This may seem like a lot of extra xml, but it can really help with configuration reuse, or providing simpler mechanisms for overriding properties for unit tests. Of course if you find yourself wrapping structs or arrays with components just because you are working with ColdSpring, well, now you don't have to.


Blogger Dan Wilson said...

This is very nice and handy. I often find I create component wrappers for structs just to refer to them with the ref="bean" syntax.

This new functionality removes an unnecessary layer. Thanks for the update.


12:57 PM  

Post a Comment

<< Home