ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Twelve Best Practices For Spring XML Configurations
Pages: 1, 2, 3

4. Prefer type over index for constructor argument matching

Spring allows you to use a zero-based index to solve the ambiguity problem when a constructor has more than one arguments of the same type, or value tags are used. For example, instead of:

    <bean id="billingService"
        <constructor-arg index="0" value="lizjason"/>
        <constructor-arg index="1" value="100"/>

It is better to use the type attribute like this:

    <bean id="billingService"
        <constructor-arg type="java.lang.String"
        <constructor-arg type="int" value="100"/>

Using index is somewhat less verbose, but it is more error-prone and hard to read compared to using the type attribute. You should only use index when there is an ambiguity problem in the constructor arguments.

5. Reuse bean definitions, if possible

Spring offers an inheritance-like mechanism to reduce the duplication of configuration information and make the XML configuration simpler. A child bean definition can inherit configuration information from its parent bean, which essentially serves as a template for the child beans. This is a must-use feature for large projects. All you need to do is to specify abstract=true for the parent bean, and the parent reference in the child bean. For example:

    <bean id="abstractService" abstract="true"
        <property name="companyName"

    <bean id="shippingService"
        <property name="shippedBy" value="lizjason"/>

The shippingService bean inherits the value lizjason for the companyName property from the abstractService bean. Note that if you do not specify a class or factory method for a bean definition, the bean is implicitly abstract.

6. Prefer assembling bean definitions through ApplicationContext over imports

Like imports in Ant scripts, Spring import elements are useful for assembling modularized bean definitions. For example:

        <import resource="billingServices.xml"/>
        <import resource="shippingServices.xml"/>
        <bean id="orderService"

However, instead of pre-assembling them in the XML configurations using imports, it is more flexible to configure them through the ApplicationContext. Using ApplicationContext also makes the XML configurations easy to manage. You can pass an array of bean definitions to the ApplicationContext constructor as follows:

    String[] serviceResources =
    ApplicationContext orderServiceContext = new

Pages: 1, 2, 3

Next Pagearrow