Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Integration Testing for Spring Applications with JNDI Connection Pools

DZone's Guide to

Integration Testing for Spring Applications with JNDI Connection Pools

· Java Zone ·
Free Resource

Java-based (JDBC) data connectivity to SaaS, NoSQL, and Big Data. Download Now.

We all know we need to use connection pools where ever we connect to a database. All of the modern drivers using JDBC type 4 support it. In this post we will have look at an overview ofconnection pooling in spring applications and how to deal with same context in a non JEE enviorements (like tests). 
Most examples of connecting to database in spring is done using  DriverManagerDataSource. If you don't read the documentation properly then you are going to miss a very important point.
NOTE: This class is not an actual connection pool; it does not actually pool Connections. It just serves as simple replacement for a full-blown connection pool, implementing the same standard interface, but creating new Connections on every call.
Useful for test or standalone environments outside of a J2EE container, either as a DataSource bean in a corresponding ApplicationContext or in conjunction with a simple JNDI environment. Pool-assuming Connection.close() calls will simply close the Connection, so any DataSource-aware persistence code should work.
Yes, by default the spring applications does not use pooled connections. There are two ways to implement the connection pooling. Depending on who is managing the pool. If you are running in a JEE environment, then it is prefered use the container for it. In a non-JEE setup there are libraries which will help the application to manage the connection pools. Lets discuss them in bit detail below.

1. Server (Container) managed connection pool (Using JNDI)

When the application connects to the database server, establishing the physical actual connection takes much more than the execution of the scripts. Connection pooling is a technique that was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provide access to a database resource. The  JavaWorld article gives a good overview about this.


In a J2EE container, it is recommended to use a JNDI DataSource provided by the container. Such a DataSource can be exposed as a DataSource bean in a Spring ApplicationContext via JndiObjectFactoryBean, for seamless switching to and from a local DataSource bean like this class.


The below articles helped me in setting up the data source in JBoss AS.

3.  JBoss Wiki
Next step is to use these connections created by the server from the application. As mentioned in the documentation you can use the  JndiObjectFactoryBean for this. It is as simple as below
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
	<property name="jndiName" value="java:/my-ds"/>
</bean>


If you want to write any tests using springs "SpringJUnit4ClassRunner" it can't load the context becuase the JNDI resource will not be available.
For tests, you can then either set up a mock JNDI environment through Spring's SimpleNamingContextBuilder, or switch the bean definition to a local DataSource (which is simpler and thus recommended). 
As I was looking for a good solutions to this problem (I did not want a separate context for tests) this  SO answer helped me. It sort of uses the various tips given in the Javadoc to good effect. The issue with the above solution is the repetition of code to create the JNDI connections. I have solved it using a customized runner  SpringWithJNDIRunner. This class adds the JNDI capabilities to the SpringJUnit4ClassRunner. It reads the data source from "test-datasource.xml" file in the class path and binds it to the JNDI resource with name "java:/my-ds". After the execution of this code the JNDI resource is available for the spring container to consume.
import javax.naming.NamingException;
import org.junit.runners.model.InitializationError;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.mock.jndi.SimpleNamingContextBuilder;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
 * This class adds the JNDI capabilities to the SpringJUnit4ClassRunner.
 * @author mkadicha
 * 
 */
public class SpringWithJNDIRunner extends SpringJUnit4ClassRunner {
    public static boolean isJNDIactive;
    /**
     * JNDI is activated with this constructor.
     * 
     * @param klass
     * @throws InitializationError
     * @throws NamingException
     * @throws IllegalStateException
     */
    public SpringWithJNDIRunner(Class<?> klass) throws InitializationError,
            IllegalStateException, NamingException {
        super(klass);
        synchronized (SpringWithJNDIRunner.class) {
            if (!isJNDIactive) {
                ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                        "test-datasource.xml");
                SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder();
                builder.bind("java:/my-ds",
                        applicationContext.getBean("dataSource"));
                builder.activate();
                isJNDIactive = true;
            }
        }
    }
}
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="" />
		<property name="url" value="" />
		<property name="username" value="" />
		<property name="password" value="" />
	</bean>
</beans>
To use this runner you just need to use the annotation  @RunWith(SpringWithJNDIRunner.class) in your test. This class extends SpringJUnit4ClassRunner beacuse a there can only be one class in the @RunWith annotation. The JNDI is created only once is a test cycle. This class provides a clean solution to the problem.

2. Application managed connection pool

If you need a "real" connection pool outside of a J2EE container, consider Apache's Jakarta Commons DBCP or C3P0. Commons DBCP's BasicDataSource and C3P0's ComboPooledDataSource are full connection pool beans, supporting the same basic properties as this class plus specific settings (such as minimal/maximal pool size etc).
Below user guides can help you configure this.

The below articles speaks about the general guidelines and best practices in configuring the connection pools.


Note:- All the text in italics are copied from the spring documentation of the DriverManagerDataSource.

Connect any Java based application to your SaaS data.  Over 100+ Java-based data source connectors.

Topics:

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}