How to Configure JNDI DataSource in Tomcat 8 with Java Configuration:
Solution 1
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.
Solution 2
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>
![samadadi](https://i.stack.imgur.com/Os9fr.jpg?s=256&g=1)
samadadi
I am a web developer & I am using GO & Javascript in my daily programming. I love C language & I use it in GUI programming & low level stuff.
Updated on June 14, 2022Comments
-
samadadi about 2 years
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>