iBatis DAO as Spring managed beans

Posted by Cliff Fenwick Gibb Cliff Fenwick Gibb   star
Options

By defining the DAOs as Spring managed beans, these beans are instantiated when the application loads, and are available within the application through the context object.
This makes the task of getting a reference to the DAOs very simple.

Prepare the Web.xml


Within your application web.xml, you will have a 'context-param' defined. For example:
  <context-param>
    <param-name>
    contextConfigLocation
    </param-name>
    <param-value>
      /WEB-INF/conf/applicationContext-jdbc.xml
      /WEB-INF/conf/securityContext.xml
    </param-value>
  </context-param>

In this sample, it is the "applicationContext-jdbc.xml" where all of the Spring managed beans are defined.

Define the Spring managed beans


In my sample, these definitions are to be found within 'applicationContext.xml'.
I have uploaded a stripped-down version of this file to demonstrate how to define these beans:
applicationContext-jdbc.xml
As you will see, the sqlMapClient is passed to the DAOImpl in the contructor. This will only work if you have modified the DAOImpl classes to extend SqlMapClientDaoSupport (mentioned in previous blog entry)

Use the Spring managed beans


Now that the Spring beans are available, they may be requested from the application context.
For example, within a controller class, you may have the following:
BusinessDAO businessDAO = (BusinessDAO)context.getBean("businessDAO");

Now with the DAO, you may proceed to make a query!
Business business = businessDAO.selectByPrimaryKey(id);

Loading...