Skip to content

Instantly share code, notes, and snippets.

@lacek
Last active August 29, 2015 14:24
Show Gist options
  • Save lacek/82a21827fb55d4ccd6b6 to your computer and use it in GitHub Desktop.
Save lacek/82a21827fb55d4ccd6b6 to your computer and use it in GitHub Desktop.
Specify data source using JNDI resource in Spring

Setting:

  • Ubuntu 14
  • Tomcat 7
  • Spring 3
  • MySQL 5.6

Install JDBC connector

wget http://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.36.tar.gz
tar -xzf mysql-connector-java-5.1.36.tar.gz
cp mysql-connector-java-5.1.36-bin.jar /usr/share/java
ln -s /usr/share/java/mysql-connector-java-5.1.36-bin.jar /usr/share/java/mysql-connector-java.jar
ln -s /usr/share/java/mysql-connector-java.jar /usr/share/tomcat7/lib/mysql-connector-java.jar

Defining resource in Tomcat

In /var/lib/tomcat7/server.xml

<Server>
    <!-- ... -->
    <GlobalNamingResources>
        <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
                    username="dataUserName" password="topSecret" driverClassName="com.mysql.jdbc.Driver"
                    url="jdbc:mysql://localhost:3306/database"/>
    </GlobalNamingResources>
    <!-- ... -->
</Server>

Linking Resource in Application

In context.xml:

<Context path="myAppPath" docBase="MyApp" reloadable="true">
    <!--...-->
    <ResourceLink name="jdbc/MyLocalDB" global="jdbc/MyDB" type="javax.sql.DataSource"/>
    <!--...-->
</Context>

Specifying Data Source

In applicationContext.xml, create the following bean:

<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
</bean>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment