Five ‘s Weblog

October 29, 2007

Autowire in Spring

Filed under: Spring — by powerdream5 @ 8:32 pm
Tags: , , , ,

         At the beginning, let’s talk about the function of autowire in spring briefly. In order to save the programmers’ time and effort in writing the spring configuration files by hand, Spring framework introduces the autowire function. To be honest, this function is pretty useful sometimes, but I don’t recommend to use it, since it always bring some problems confusing you. In the following, I would like to show you an example to exmplain why I avert autowire.


        <beans default-autowire=”autodetect”> <!–autowire is the cause of exception–>
                <bean id=”dataSource” class=”org.apache.commons.dbcp.BasicDataSource”>
                <bean id=”sessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean”>
               <bean id=”cronReportTrigger” class=”org.springframework.scheduling.quartz.CronTriggerBean”>
               <bean id=”schedulerFactoryBean” class=”org.springframework.scheduling.quartz.SchedulerFactoryBean”>
                         <property name=”triggers”>
                                       <ref bean=”cronReportTrigger”/>

        In my example, firstly, I configure Hibernate. In order to execute a method in a specific time, I configure Quartz. Both of the two configuration processes are so easy that you will not come across any obstacles. However, if you set the autowire properties, when you start the server, you would get the exception: “Failure obtaining db row lock: Table ‘hibernate.qrtz_locks’ doesn’t exist“. I believe you must be confused, and you would ask why the SchedulerFactoryBean class has relationship with Hibernate.

        In fact, this exception is caused by the autowire property of Spring. The org.springframework.scheduling.quartz.SchedulerFactoryBean has a method named setDataSource. Because we set the autowire properiy as “autodetect”, and we also configure database source in our application, the spring container will inject this database source into the SchedulerFactoryBean class automatically, then SchedulerFactoryBean class will looking the database for tasks. There is no task in your database, therefore, you get the exception. Fortunately, as soon as you realize the cause of the exception, it is easy to handle it by removing the autowire property. Then, restart your server, things goes well.

         From this example, we can see that the autowire property may bring some problems over our expectation. Therefore, use this property cautiously!


Create a free website or blog at