I am working on a legacy application that uses Tomcat 7.0.64 and we want to configure apache dbcp2 connection pool as a resource in Tomcat. The application runs Spring 4.x and Hibernate 4.x. After reading Tomcat documentation when I try to access the dbcp2 connection pool from Spring application I am getting the following exception -
javax.naming.NamingException: Could not create resource factory instance [Root exception is java.lang.ClassNotFoundException: org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory]
Why is org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory
being used even though the "factory" attribute added in server.xml
is of type org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory
. Below mentioned are the details of the configurations -
Added following in server.xml
-
<GlobalNamingResources>
<Resource name="jdbc/mytestDB"
auth="Container"
factory="org.apache.tomcat.dbcp.dbcp2.BasicDataSourceFactory"
type="javax.sql.DataSource"
username="test"
password="test"
driverClassName="oracle.jdbc.driver.OracleDriver"
description="test db"
url="jdbc:oracle:thin:@mytestDB:1521/mytestDB"
maxActive="15"
maxIdle="5"/>
</GlobalNamingResources>
Added following in web.xml -
<resource-ref>
<description>PVO Database</description>
<res-ref-name>jdbc/mytestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Added following maven dependencies -
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-dbcp</artifactId>
<version>8.5.4</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.1</version>
</dependency>
In test class added the following -
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:comp/env");
DataSource ds = envContext.lookup("jdbc/mytestDB"); // This line gives the above mentioned error.
Connection connection = ds != null ? ds.getConnection() : null;
Fixed the issue by adding the following JVM property in tomcat -configure
data sources to be retrieved via JNDI -
JAVA_OPTS="${JAVA_OPTS} -
Djavax.sql.DataSource.Factory="org.apache.commons.dbcp2.BasicDataSourceFactory"
However we decided to upgrade tomcat version.