My blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://utku-utkan.appspot.com/
and update your bookmarks.

Pages

Wednesday, August 6, 2008

To be, or not to be auto-wired, that is the question.

If properly used, Spring's auto-wire feature might be really handy and it can reduce the volume of your configuration files. It is possible to auto-wire beans by their types or names; but my favorite is auto-wiring by name. You can find more information about this feature here. But now, I want to emphasize one big disadvantage of auto-wiring.

Consider that we are developing an application that will store users and their authorities (roles). In this application, there will be two Data Access Objects (DAO) to deal with User and Authority entity classes, and a service class that depends on these two DAO classes.

In this scenario without using the auto-wire feature our configuration file will look like:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

    <!-- DAO Beans -->

    <bean id="userDao"
        class="org.hoydaa.autowire.dao.impl.UserDaoImpl" />

    <bean id="authorityDao"
        class="org.hoydaa.autowire.dao.impl.AuthorityDaoImpl" />

    <!-- Service Beans -->

    <bean id="userService"
        class="org.hoydaa.autowire.service.impl.UserServiceImpl"
        p:userDao-ref="userDao"
        p:authorityDao-ref="authorityDao" />

</beans>


However, when the auto-wire feature is enabled, configuration file will be as simple as:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
    default-autowire="byName">

    <!-- DAO Beans -->

    <bean id="userDao"
        class="org.hoydaa.autowire.dao.impl.UserDaoImpl" />

    <bean id="authorityDao"
        class="org.hoydaa.autowire.dao.impl.AuthorityDaoImpl" />

    <!-- Service Beans -->

    <bean id="userService"
        class="org.hoydaa.autowire.service.impl.UserServiceImpl" />

</beans>


Although the XML file is way more simple, the dependency information between the beans is lost. In my opinion, it is very good to have such a place listing all the dependency between the beans clearly. By looking at this simple configuration file I cannot say that the User Service depends on User DAO and Authority DAO. When the auto-wire feature is enabled, the only way to learn this information is to inspect all the Java classes.