About Manu PK

Manu develops software applications using Java and related technologies. Geek, Tech Blogger, open source and web enthusiast.

Integration Testing for Spring Applications with JNDI Connection Pools

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 supports it. In this post we will have look at an overview of connection 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)

con-pool

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.

  1. DebaJava Post
  2. JBoss Installation Guide
  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.

  1. Spring Docs
  2. C3P0 Userguide
  3. DBCP Userguide

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

  1. SO question on Spring JDBC Connection pools
  2. Connection pool max size in MS SQL Server 2008
  3. How to decide the max number of connections
  4. Monitoring the number of active connections in SQL Server 2008

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


+ one = 5



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close