Reputation: 3370
How to Configure JNDI DataSource in Java Configuration File Instead of Following Code Snippet in "web.xml" Servlet Context:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/DatabaseName</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Upvotes: 3
Views: 17922
Reputation: 1691
It can be done in 3 steps:
Step 1:
Add below entry in tomcat conf/server.xml under GlobalNamingResources tag.
<Resource auth="Container" driverClassName="DB_Drive_class-name" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/MyJNDI" password="&&&&&&&&&&&&&" type="javax.sql.DataSource" url="jdbc:db2://URL:PORT/DBNAME" username="&&&&&&&&&"/>
Step 2:
Add below entry in tomcat conf/context.xml under root context tag.
<ResourceLink name="jdbc/MyJNDI" global="jdbc/MyJNDI" type="javax.sql.DataSource"/>
Step 3:
Add DataSource ref in web.xml
<resource-ref>
<description>DB2 Datasource</description>
<res-ref-name>jdbc/MyJNDI</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
Note: This is a global Tomcat configuration and DataSource can be shared with different applications.
Upvotes: 0
Reputation: 3370
Note: Don't Forget to Copy the "mysql-connector-java-5.1.36.jar" Into Tomcat's "lib" Subfolder in Main Installation Folder.
First: Add following Dependency in Your "pom.xml" File:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
Second: Create META-INF Folder and "context.xml" File in "webapp" Root Folder Like the Following Picture:
Third: Add the Following Code Snippet in "context.xml" File:
<?xml version='1.0' encoding='utf-8'?>
<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
maxActive="50" maxIdle="30" maxWait="10000"
username="DatabaseUsername" password="DatabasePasssword"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/DatabaseName"/>
</Context>
Fourth: Create the Following Bean in Spring Context Configuration File:
@Bean
public DataSource dataSource() {
JndiDataSourceLookup dataSource = new JndiDataSourceLookup();
dataSource.setResourceRef(true);
return dataSource.getDataSource("jdbc/DatabaseName");
}
Note: "jdbc/DatabaseName" is "name" Attribute that We Added Already in "context.xml" File.
Upvotes: 9
Reputation: 27373
To complete SMGs answer: for xml-configured Spring, I use the following code (note the "webapp" profile, as for unit-tests you need to have a webserver-independent datasource)
<beans profile="webapp">
<!-- get dataSources from web-container -->
<bean name="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
<property name="jndiName" value="java:comp/env/jdbc/DatabaseName" />
<property name="resourceRef" value="true" />
</bean>
</beans>
Upvotes: 2