Thursday, 21 May 2009

Method C : Delegate Struts Action management to the Spring framework

Here we are going to delegate Struts action management to the Spring framework.

All you have to do is...

For each action that uses Spring, you need to define the action mapping to use org.springframework.web.struts.DelegatingActionProxy and declare a matching (action "path" == bean "name") Spring bean for the actual Struts action. This is an example of an action that requires an instance of UserDatabase:

Note the changes in struts-config file.

Inside action-mappings instead of declaring the action's class name, it registers the name of Spring's proxy class. The DelegatingActionProxy class uses the action mapping name to look up the action in the Spring context. This is the context that was declared with ContextLoaderPlugIn.


<struts-config>
<form-beans>
<form-bean name="searchForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="id" type="java.lang.Long"/>
</form-bean>

</form-beans>

<global-forwards type="org.apache.struts.action.ActionForward">
<forward name="welcome" path="/welcome.do"/>
<forward name="searchEntry" path="/searchEntry.do"/>
<forward name="searchSubmit" path="/searchSubmit.do"/>
</global-forwards>

<action-mappings>
<action path="/welcome" forward="/WEB-INF/pages/welcome.htm"/>

<action path="/searchEntry" forward="/WEB-INF/pages/search.jsp"/>

<action path="/searchSubmit"
type="org.springframework.web.struts.DelegatingActionProxy"
input="/searchEntry.do"
validate="true"
name="searchForm">
<forward name="success" path="/WEB-INF/pages/detail.jsp"/>
<forward name="failure" path="/WEB-INF/pages/search.jsp"/>
</action>

</action-mappings>

<message-resources parameter="ApplicationResources"/>

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>


<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>


</struts-config>



The corresponding Spring bean configuration...


<beans>

<bean id="employee_1" class="struts.spring.employee.beans.Employee">
<property name="id" value="1" />
<property name="name" value="Sneha" />
</bean>

<bean id="employee_2" class="struts.spring.employee.beans.Employee">
<property name="id" value="2" />
<property name="name" value="Prashant" />
</bean>

<bean id="employeeService" class="struts.spring.employee.business.EmployeeImpl">
<property name="employees">
<map>
<entry key="1">
<ref bean="employee_1" />
</entry>
<entry key="2">
<ref bean="employee_2" />
</entry>
</map>
</property>
</bean>

<bean name="/searchSubmit"
class="struts.spring.employee.actions.FindEmployeeAction">
<property name="employeeService">
<ref bean="employeeService"/>
</property>
</bean>

</beans>



Merits:
1. As the action is under Spring's control, it populates the action's JavaBean properties and leaves the door open to applying features such as Spring's AOP interceptors.


The action-delegation solution is the best of the three.

Hope it will be useful...

References : http://www.ibm.com/developerworks/java/library/j-sr2.html

Method B : Override the Struts RequestProcessor with Spring's DelegatingRequestProcessor

To avoid the above disadvantage of coupling the Struts Action to the Spring framework, you can override the Struts RequestProcessor processor with the org.springframework.web.struts.DelegatingRequestProcessor class.

To do the above just use tag to override the default Struts RequestProcessor with the DelegatingRequestProcessor in Struts-config file. Then register the action in Spring config file where you register other beans.


<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
<form-beans>
<form-bean name="searchForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="id" type="java.lang.Long"/>
</form-bean>

</form-beans>

<global-forwards type="org.apache.struts.action.ActionForward">
<forward name="welcome" path="/welcome.do"/>
<forward name="searchEntry" path="/searchEntry.do"/>
<forward name="searchSubmit" path="/searchSubmit.do"/>
</global-forwards>

<action-mappings>
<action path="/welcome" forward="/WEB-INF/pages/welcome.htm"/>

<action path="/searchEntry" forward="/WEB-INF/pages/search.jsp"/>

<action path="/searchSubmit"
type="struts.spring.employee.actions.FindEmployeeAction"
input="/searchEntry.do"
validate="true"
name="searchForm">
<forward name="success" path="/WEB-INF/pages/detail.jsp"/>
<forward name="failure" path="/WEB-INF/pages/search.jsp"/>
</action>

</action-mappings>

<message-resources parameter="ApplicationResources"/>

<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>


<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>


</struts-config>



and here is Spring config file. Register the action here and remember name attribute to match the struts-config action mapping name.
employeeService property will be populated at runtime using getter injection.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="employee_1" class="struts.spring.employee.beans.Employee">
<property name="id" value="1" />
<property name="name" value="Sneha" />
</bean>

<bean id="employee_2" class="struts.spring.employee.beans.Employee">
<property name="id" value="2" />
<property name="name" value="Prashant" />
</bean>

<bean id="employeeService" class="struts.spring.employee.business.EmployeeImpl">
<property name="employees">
<map>
<entry key="1">
<ref bean="employee_1" />
</entry>
<entry key="2">
<ref bean="employee_2" />
</entry>
</map>
</property>
</bean>

<bean name="/searchSubmit"
class="struts.spring.employee.actions.FindEmployeeAction">
<property name="employeeService">
<ref bean="employeeService"/>
</property>
</bean>

</beans>



Now your action class extend the Struts's org.apache.struts.action.Action Class instead of Spring ActionSupport Class.


public class FindEmployeeAction extends Action{

private EmployeeI employeeService;

public EmployeeI getEmployeeService() {
return employeeService;
}

public void setEmployeeService(EmployeeI employeeService) { //1
this.employeeService = employeeService;
}

public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

DynaActionForm searchForm = (DynaActionForm) form;
Long id = Long.parseLong(searchForm.get("id").toString());

System.out.println("Inside FindEmployeeAction_2 id = "+id);

Employee employee = getEmployeeService().findEmployeeById(id);

if (null == employee) {
System.out.println("employee not found");
return mapping.findForward("failure") ;
}

System.out.println("employee found");
request.setAttribute("emp", employee);
return mapping.findForward("success");
}
}



As you have seen at 1 employeeService JavaBean property will be automatically populated by the DelegatingRequestProcessor.

Merits:
1. Protects the Struts action from knowing it's being managed by Spring while giving you all the benefits of Spring's action management framework.
2. Because your Struts actions are oblivious to the existence of Spring, you can swap out Spring for some other inversion of control container without refactoring your Struts code.
3. This approach is definitely better than the first one

Demerits:
1. If you were using a different RequestProcessor, then you would need to integrate the Spring DelegatingRequestProcessor manually.
2. The added code would become a maintenance hassle and would also reduce your application's flexibility going forward. Moreover, there has been some talk of replacing the Struts RequestProcessor with a chain of command. Such a change would negatively impact the longevity of this solution.

Hope it will be useful...

References : http://www.ibm.com/developerworks/java/library/j-sr2.html

Method A : Using Spring's ActionSupport Class to integrate Struts

Here we are going to use Spring's ActionSupport class to integrate Struts.

Action classes of Struts framework do not get started as Spring framework beans, thus cannot be wired through Dependency Injection

If the Action class wants to access beans of Spring framework, it has to access them manually.

Instead of extending Action class, you can extend Spring's org.springframework.web.struts.ActionSupport Class which provides getWebApplicationContext() method to obtain a Spring context

Action Support provides a reference to the current Spring application context, e.g. for bean lookup or resource loading
- Auto-detects a ContextLoaderPlugIn context, falling back to the root WebApplicationContext.
- For typical usage, i.e. accessing middle tier beans, use a root WebApplicationContext.

Below is how your Struts Action Class look like :


public class FindEmployeeAction extends ActionSupport{ //1
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

DynaActionForm searchForm = (DynaActionForm) form;
Long id = Long.parseLong(searchForm.get("id").toString());

System.out.println("Inside FindEmployeeAction id = "+id);

ApplicationContext ctx = getWebApplicationContext(); //2
EmployeeI employeeService = (EmployeeI) ctx.getBean("employeeService"); //3

Employee employee = employeeService.findEmployeeById(id);

if (null == employee) {
return mapping.findForward("failure") ;
}

request.setAttribute("emp", employee);
return mapping.findForward("success");
}
}



Let see how the above Action Class is different from Traditional Action Class and how can it provide a reference to the current Spring context.

1. Extend ActionSupport(org.springframework.web.struts.ActionSupport) Class instead Action Class.
2. ApplicationContext refernce is obtained through getWebApplicationContext() method which is there in ActionSupport Class.
3. Look up for Spring bean using the context reference you have obtained.

Have a look at Spring-config file also.


<beans>

<bean id="employee_1" class="struts.spring.employee.beans.Employee">
<property name="id" value="1" />
<property name="name" value="Sneha" />
</bean>

<bean id="employee_2" class="struts.spring.employee.beans.Employee">
<property name="id" value="2" />
<property name="name" value="Prashant" />
</bean>

<bean id="employeeService" class="struts.spring.employee.business.EmployeeImpl">
<property name="employees">
<map>
<entry key="1">
<ref bean="employee_1" />
</entry>
<entry key="2">
<ref bean="employee_2" />
</entry>
</map>
</property>
</bean>


</beans>



Merits :
1. Very Simple and easy to understand.

Demerits:
1. It couples the Struts action to the Spring framework. If you ever decide to replace Spring, you would have to rewrite the code.
2. As the Struts action isn't under Spring's control, it can't reap the benefits of Spring AOP.
3. Useful when using multiple independent Spring contexts, but for the most part it's not as desirable a solution as the other two choices.


Hope it will be useful...

References : http://www.ibm.com/developerworks/java/library/j-sr2.html

Wednesday, 20 May 2009

Integrating Spring with Struts

Key to the Spring Framework is the freedom to choose what works best for your application. Spring offers you choices when building web applications, too. Although Spring offers its own very capable web framework, you are free to choose another if you’d like and still be able to take advantage of Spring in the other layers of your application.

Advantages of integrating a Struts application into the Spring framework:

1. Spring was explicitly designed to resolve some of the real-world problems of JEE, such as complexity, poor performance, testability, and much more.
2. Second, the Spring framework includes an AOP implementation that lets you apply aspect-oriented techniques to normal object-oriented code.

Both Struts and Spring frameworks have their merits and drawbacks, but most would agree that Struts is still king when it comes to MVC. Many development teams have learned to rely on Struts as the foundation for building quality software under strict deadlines. With so much momentum behind Struts, even development teams that would like to integrate features of the Spring framework don't want to switch to Spring MVC. The good news is that you don't have to. The Spring architecture allows you to connect Struts as your Web framework to Spring-based business and persistence layers.

Below we will see three approaches to integrating Struts applications into the Spring framework and discuss their merits and demerits.

A. Using Spring's ActionSupport class to integrate Struts.
B. Override the Struts RequestProcessor with Spring's DelegatingRequestProcessor.
C. Delegate Struts Action management to the Spring framework.

Whatever technique you use, you will need to add the Spring ContextLoaderPlugin to load the Spring application context for the Struts ActionServlet. Simply add the plug-in to your struts-config.xml file as you would any other plug-in, as shown below:


<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/>
</plug-in>



and here is the code for my bean, interface and impl which is common to all three methodologies.


public class Employee implements Serializable{

private Long id;
private String name;

public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}

}

public interface EmployeeI {

public Employee findEmployeeById(Long id);

public int getNoOfEmployees();
}

public class EmployeeImpl implements EmployeeI{

private Map<Long,Employee> employees = new HashMap<Long,Employee>();

public Employee findEmployeeById(Long id){
System.out.println("Inside findEmployeeById id = "+id);
Employee employee = (Employee)employees.get(id.toString());
System.out.println("Employee found = "+employee);
return employee;
}

public int getNoOfEmployees(){
return employees.size();
}

public Map<Long, Employee> getEmployees() {
return employees;
}

public void setEmployees(Map<Long, Employee> employees) {
this.employees = employees;
}

}


In my Impl Class I am having HashMap which is set at runtime using Spring's getter injection.

I have divided three methodologies into three ariticles as dont want to make it messy. Complete code is provided in the respective articles.

Method A : A. Using Spring's ActionSupport class to integrate Struts.

Method B : B. Override the Struts RequestProcessor with Spring's DelegatingRequestProcessor.

Method C : C. Delegate Struts Action management to the Spring framework.

If you directly want to go the best method. Find out my continuation article,
C. Delegate Struts Action management to the Spring framework.

Thursday, 14 May 2009

RMI using Spring

Let us look at Spring’s support to Remoting.

Spring supports remoting for several different Remote Procedure Call models, including Remote Method Invocation (RMI), Caucho’s Hessian and Burlap, and Spring’s own HTTP invoker.

Spring offers a POJO-based programming model for both your server and client, no matter which remoting solution you choose. This is accomplished using a proxy factory bean that enables you to wire remote services into properties of your other beans as if they were local objects.

The client makes calls to the proxy as if the proxy were providing the service functionality. The proxy communicates with the remote service on behalf of the client. It handles the details of connecting and making remote calls to the remote service.

If the call to the remote service results in a java.rmi.RemoteException, the proxy handles that exception and rethrows it as an unchecked
org.springframework.remoting.RemoteAccessException. Remote exceptions usually signal problems such as network or configuration issues that can’t be gracefully recovered from. Since there’s usually very little that a client can do to gracefully recover from a remote exception, rethrowing a RemoteAccessException makes it optional for the client to handle the exception.

Spring simplifies the RMI model by providing a proxy factory bean that enables you to wire RMI services into your Spring application is if they were local JavaBeans. Spring also provides a remote exporter that makes short work of converting your Spring-managed beans into RMI services.

Spring’s RmiProxyFactoryBean is a factory bean that creates a proxy to an RMI service. RmiProxyFactoryBean produces a proxy object that talks to remote RMI services on behalf of the client. The client talks to the proxy through the service’s interface as if the remote service were just a local POJO.

RmiProxyFactoryBean certainly simplifies the use of RMI services in a Spring application. But that’s only half of an RMI conversation.

Spring provides an easier way to publish RMI services. Instead of writing RMI-specific classes with methods that throw RemoteException, you simply write a POJO that performs the functionality of your service. Spring handles the rest.

For a typical Spring Application we need the following files:

1. An interface that defines the functions.

2. An Implementation that contains properties, its setter and getter methods, functions etc.

3. A XML file called Spring configuration file.

4. Client program that uses the function

Because the service interface doesn’t extend java.rmi.Remote and none of its methods throw java.rmi.RemoteException, this trims the interface down a bit. But more importantly, a client accessing the service through this interface will not have to catch exceptions that they probably won’t be able to deal with. Instead of generating a server skeleton and client stub using rmic and manually adding it to the RMI registry (as you would in conventional RMI), we’ll use Spring’s RmiServiceExporter.

RmiServiceExporter exports any Spring-managed bean as an RMI service. RmiServiceExporter works by wrapping the bean in an adapter class. The adapter class is then bound to the RMI registry and proxies requests to the service class.

The simplest way to use RmiServiceExporter to expose the employeeService bean as an RMI service is to configure it in Spring with the following XML:


<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="employee-service"/>
<property name="service" ref="employeeService"/>
<property name="serviceInterface" value="rmi.common.EmployeeI"/>
<property name="registryPort" value="1234"/>
</bean>



Here the employeeService bean is wired into the service property to indicate that RmiServiceExporter is going to export the bean as an RMI service. ServiceName property names the RMI service and the serviceInterface property specifies the interface implemented by the service.


<bean id="employeeService" class="rmi.server.EmployeeImpl">
</bean>


Now let us look at an example...

Let us have simple employee recruitment service exposed through EmployeeI interface which contains methods to add, remove and get number of employees.


public class Employee implements Serializable {
private String name;
private String address;

public Employee(String name,String address){
this.name = name;
this.address = address;
}

// getters and setters
}


public interface EmployeeI {

public void addEmployee(Employee employee);

public void removeEmployee(Employee employee);

public List<Employee> getEmployees();

}



Here is the implementation for EmployeeI interface.


public class EmployeeImpl implements EmployeeI{

private List<Employee> employees = new ArrayList<Employee>();

public void addEmployee(Employee employee) {
employees.add(employee);
}

public void removeEmployee(Employee employee){
employees.remove(employee);
}

public List<Employee> getEmployees() {
return employees;
}
}



On the server side, we need to configure Spring to export the service through RMI. As we discussed earlier we can do it by RmiServiceExporter.
The interface can be accessed by using RmiProxyFactoryBean, or via plain RMI in case of a traditional RMI service. The RmiServiceExporter explicitly supports the exposing of any non-RMI services via RMI invokers. Of course, we first have to set up our service in the Spring container:


<beans>
<bean id="employeeService" class="rmi.server.EmployeeImpl"/>

<bean class="org.springframework.remoting.rmi.RmiServiceExporter">
<property name="serviceName" value="employee-service"/>
<property name="service" ref="employeeService"/>
<property name="serviceInterface" value="rmi.common.EmployeeI"/>
<property name="registryPort" value="1234"/>
</bean>
</beans>



Now to run the server side service you need Spring context initialization.


public class EmpServerDemo {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi/server/rmi-server-context.xml");
}
}


Now let us have a look at client side.

To link in the service on the client, we'll create a separate Spring container, containing the simple object and the service linking configuration bits:


<beans>
<bean id="employeeService" class="org.springframework.remoting.rmi.RmiProxyFactoryBean">
<property name="serviceUrl" value="rmi://localhost:1234/employee-service"/>
<property name="serviceInterface" value="rmi.common.EmployeeI"/>
</bean>
</beans>



You can make client calls through the below code...


public class EmpClientDemo {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("rmi/client/rmi-client-context.xml");
EmployeeI employee = (EmployeeI) ctx.getBean("employeeService");
employee.addEmployee(new Employee("Prashant", "address1"));
employee.addEmployee(new Employee("Sneha", "address2"));
List<Employee> employees = employee.getEmployees();
System.out.println("Total number of employees: " + employees.size());
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
Employee emp = (Employee) it.next();
System.out.println(" " + emp);
}
}
}



Therefore, the client will not be aware of the fact that the service is running remote and even less about the fact that its method calls are marshaled through RMI. The Spring bean configuration file takes care of these details, so the client code will not be affected if we change the remoting strategy or even if we choose to run the service in-process.

First run the EmpServerDemo in one console to launch the RMI server and then run the EmpClientDemo in another console.

RMI with Spring is as simple as that.

Hope it will be useful....

References :

Spring in Action by Craig Walls.

http://cosminaru.ro/blog/2006/11/02/spring-by-examples-rmi/.

Thursday, 7 May 2009

Persistence in Spring

Last week I read Spring in Action by Craig Walls.

It was very good book and I found it very informative.

I would like to share few quotations from the book, which gives generic idea about Persistance in Spring.

Spring comes with a family of data access frameworks that integrate with a variety of data access technologies. Whether you are persisting your data via direct JDBC, iBATIS, or an object relational mapping (ORM) framework like Hibernate, Spring removes the tedium of data access from your persistence code. Instead, you can lean on Spring to handle the low-level data access work for you so that you can turn your attention to managing your application’s data.

Spring supports persistence mechanisms like JDBC, Hibernate, the Java Persistence API (JPA), iBATIS etc.

DAO stands for data access object, which perfectly describes a DAO’s role in an application. DAOs exist to provide a means to read and write data to the database.

They should expose this functionality through an interface by which the rest of the application will access them. This has a couple of advantages. First, it makes your service objects easily testable since they are not coupled to a specific data access implementation.

In addition, the data access tier is accessed in a persistence technology–agnostic manner. That is, the chosen persistence approach is isolated to the DAO while only the relevant data access methods are exposed through the interface. This makes for a flexible application design and allows the chosen persistence framework to be swapped out with minimal impact to the rest of the application. If the implementation details of the data access tier were to leak into other parts of the application, the entire application would become coupled with the data access
tier, leading to a rigid application design.

One way Spring helps you insulate your data access tier from the rest of your application is by providing you with a consistent exception hierarchy that is used across all of its DAO frameworks.

In JDBC , you can’t do anything with JDBC without being forced to catch java.sql.SQLException. SQLException is treated as a “one size
fits all” exception for problems related to data access. Rather than have a different exception type for each possible problem, SQLException is sthe exception that’s thrown for all data access problems.

Even so, Hibernate’s exceptions are specific to Hibernate. As stated before, we’d like to isolate the specifics of the persistence mechanism to the data access layer. If Hibernate-specific exceptions are being thrown then the fact that we’re dealing with Hibernate will leak into the rest of the application. Either that, or you’ll be forced to catch persistence platform exceptions and rethrow them as platform-agnostic exceptions.

On one hand, JDBC’s exception hierarchy is too generic—in fact, it’s not much of a hierarchy at all. On the other hand, Hibernate’s exception hierarchy is proprietary to Hibernate. What we need is a hierarchy of data access exceptions that are descriptive but not directly associated with a specific persistence framework.

Spring’s persistence platform agnostic exceptions :
Spring JDBC provides a hierarchy of data access exceptions that solve both problems. In contrast to JDBC, Spring provides several data access exceptions, each descriptive of the problem.

Even though Spring’s exception hierarchy is far more rich than JDBC’s simple SQLException, it isn’t associated with any particular persistence solution. This means that you can count on Spring to throw a consistent set of exceptions, regardless of which persistence provider you choose. This helps to keep your persistence choice confined to the data access layer.

Spring promotes the use of unchecked exceptions. This leaves the decision of whether to catch an exception in the developer’s hands. To take advantage of Spring’s data access exceptions, you must use one of Spring’s supported data access templates.

Spring applies Template method Pattern to data access.

It separates the fixed and variable parts of the data access process into two distinct classes: templates and callbacks. Templates manage the fixed part (controlling transactions, managing resources, and handling exceptions)of the process while your custom data access code (creating statements, binding parameters, and marshaling result sets) is handled in the callbacks.

Spring comes with several templates to choose from, depending on your persistence platform choice. If you’re using straight JDBC then you’ll want to use JdbcTemplate. But if you favor one of the object-relational mapping frameworks then perhaps HibernateTemplate or JpaTemplate is more suitable. Direct wiring of the templates is fine, but Spring also provides a set of convenient DAO base classes that can manage the template for you.

The data access templates are not all there is to Spring’s data access framework. Each template also provides convenience methods that simplify data access without the need to create an explicit callback implementation. Furthermore, on top of the template-callback design, Spring provides DAO support classes that are meant to be subclassed by your own DAO classes.

When writing your application DAO implementation, you can subclass a DAO support class and call a template retrieval method to have direct access to the underlying data access template. For example, if your applicationDAO subclasses JdbcDaoSupport then you only need to call getJdbcTemplate() to get a JdbcTemplate to work with.

Just as Spring provides several data access template implementations, it also provides several DAO support classes—one for each template.

Spring’s persistence support options will depend on a data source. So, let us know how to configure Spring with a data source for the DAOs to access the database.

Configuring a data source

Regardless of which form of Spring DAO support you use, you’ll likely need to configure a reference to a data source. Spring offers several options for configuring data source beans in your Spring application, including:
1. Data sources that are defined by a JDBC driver
2. Data sources that are looked up by JNDI
3. Data sources that pool connections

1. Let us look at using JNDI data sources :

Spring applications will quite often be deployed to run within a JEE application server such as WebSphere, JBoss, or even a web container like Tomcat. These servers allow you to configure data sources to be retrieved via JNDI. The benefit of configuring data sources in this way is that they can be managed completely external to the application, leaving the application to simply ask for a data source when it’s ready to access the database. Moreover, data sources managed in an application server are often pooled for greater performance and can be hotswapped
by system administrators.

With Spring, we can configure a reference to a data source that is kept in JNDI and wire it into the classes that need it as if it were just another Spring bean. Spring’s JndiObjectFactoryBean makes it possible to retrieve any object, including data sources, from JNDI and make it available as a Spring bean.

How does JndiObjectFactoryBean retrieve a data source from JNDI:


<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="/jdbc/SampleDatasource" />
<property name="resourceRef" value="true" />
</bean>


The jndiName attribute is used to specify the name of the resource in JNDI. If only the jndiName property is set then the data source will be looked up as is. But if the application is running within a Java application server then you’ll want to set the resourceRef property to true.

When resourceRef is true, the value of jndiName will be prepended with java:comp/env/ to retrieve the data source as a Java resource from the application server’s JNDI directory. Consequently, the actual name used will be java:comp/env/jdbc/SampleDatasource.

2 Using a pooled data source :

Configuring a BasicDataSource bean is like


<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="initialSize" value="5" />
<property name="maxActive" value="10" />
</bean>


The first four properties are elemental to configuring a BasicDataSource. The driverClassName property specifies the fully qualified name of the JDBC driver class. Here we’ve configured it with the JDBC driver for the Hypersonic database. The url property is where we set the complete JDBC URL for the database. Finally, the username and password properties are used to authenticate when you’re connecting to the database. Those four basic properties define connection information for BasicData- Source. In addition, several properties can be used to configure the data source pool itself.

3. JDBC driver-based data source

The simplest data source you can configure in Spring is one that is defined through a JDBC driver. Spring offers two such data source classes to choose from (both in the org.springframework.jdbc.datasource package):

-> DriverManagerDataSource—Returns a new connection every time that a connection is requested. Unlike DBCP’s BasicDataSource, the connections
provided by DriverManagerDataSource are not pooled.

-> SingleConnectionDataSource—Returns the same connection every time that a connection is requested. Although SingleConnectionDataSource
isn’t exactly a pooled data source, you can think of it as a data source with a pool of exactly one connection.

Configuring either of these data sources is similar to how we configured DBCP’s BasicDataSource as shown above. The only difference is that since neither DriverManagerDataSource nor Single-ConnectionDataSource provides a connection pool, there are no pool configuration
properties to set.

Although SingleConnectionDataSource and DriverManagerDataSource are great for small applications and running in development, you should seriously consider the implications of using either in a production application. Because SingleConnectionDataSource has one and only one database connection to work with, it doesn’t work well in a multithreaded application. At the same time, even though DriverManagerDataSource is capable of supporting multiple threads, it incurs a performance cost for creating a new connection each time a connection is requested. Because of these limitations, using pooled data sources strongly recommend.

Hope it will be useful...