Archives for: January 2006, 25

Jan 25, 2006 : A factory bean within Spring

Spring is great at providing instances of a class to an object that depends on using one. You can also use one bean to provide multiple instances of the class to other beans:


    <bean id="list" class="java.util.ArrayList" singleton="false"/>
    <bean id="foo" class="my.FooImpl" />
        <property name="people" ref="list" />
        <property name="computers" ref="list" />
    </bean>
    <bean id="bar" class="my.BarImpl" />
        <property name="baz" ref="list" />
    </bean>

You can also have a "factory" so that a class Baz can create many Yaps (e.g. to populate a List<Yap>).


    <bean id="yap" class="my.YapImpl" singleton="false"/>
    <bean id="bar" class="my.BazImpl" />
        <lookup-method name="createNewYap" bean="yap" />
    </bean>

with Java code:


    public interface Yap { ... }
    public class YapImpl implements Yap { ... }
    public interface Baz { ... }
    public class BazImpl implements Baz {
        public getSomeYaps() {
            // I don't think Spring can provide a parameterized type implementation (e.g. the ArrayList<Yap>)
            List<Yap> yaps = new ArrayList<Yap>();
            for (int i = 0; i < 5; i++) {
                Yap yap = createNewYap();
                yap.setSomething(i*2);
                yaps.add(yap);
            }
            return yaps;
        }
        // overridden by Spring
        protected Yap createNewYap()
            return null;
        }
    }

<  January 2006  >
Mon Tue Wed Thu Fri Sat Sun
            1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31          

Categories


Archives

Misc

Syndicate this blog XML

powered by
b2evolution