How to use JNDI DataSource provided by Tomcat in Spring?

274,397

Solution 1

If using Spring's XML schema based configuration, setup in the Spring context like this:

<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:jee="http://www.springframework.org/schema/jee" xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
...
<jee:jndi-lookup id="dbDataSource"
   jndi-name="jdbc/DatabaseName"
   expected-type="javax.sql.DataSource" />

Alternatively, setup using simple bean configuration like this:

<bean id="DatabaseName" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="java:comp/env/jdbc/DatabaseName"/>
</bean>

You can declare the JNDI resource in tomcat's server.xml using something like this:

<GlobalNamingResources>
    <Resource name="jdbc/DatabaseName"
              auth="Container"
              type="javax.sql.DataSource"
              username="dbUser"
              password="dbPassword"
              url="jdbc:postgresql://localhost/dbname"
              driverClassName="org.postgresql.Driver"
              initialSize="20"
              maxWaitMillis="15000"
              maxTotal="75"
              maxIdle="20"
              maxAge="7200000"
              testOnBorrow="true"
              validationQuery="select 1"
              />
</GlobalNamingResources>

And reference the JNDI resource from Tomcat's web context.xml like this:

  <ResourceLink name="jdbc/DatabaseName"
   global="jdbc/DatabaseName"
   type="javax.sql.DataSource"/>

Reference documentation:

Edit: This answer has been updated for Tomcat 8 and Spring 4. There have been a few property name changes for Tomcat's default datasource resource pool setup.

Solution 2

With Spring's JavaConfig mechanism, you can do it like so:

@Configuration
public class MainConfig {

    ...

    @Bean
    DataSource dataSource() {
        DataSource dataSource = null;
        JndiTemplate jndi = new JndiTemplate();
        try {
            dataSource = jndi.lookup("java:comp/env/jdbc/yourname", DataSource.class);
        } catch (NamingException e) {
            logger.error("NamingException for java:comp/env/jdbc/yourname", e);
        }
        return dataSource;
    }

}

Solution 3

Assuming you have a "sampleDS" datasource definition inside your tomcat configuration, you can add following lines to your applicationContext.xml to access the datasource using JNDI.

<jee:jndi-lookup expected-type="javax.sql.DataSource" id="springBeanIdForSampleDS" jndi-name="sampleDS"/>

You have to define the namespace and schema location for jee prefix using:

xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"

Solution 4

Documentation: C.2.3.1 <jee:jndi-lookup/> (simple)

Example:

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/MyDataSource"/>

You just need to find out what JNDI name your appserver has bound the datasource to. This is entirely server-specific, consult the docs on your server to find out how.

Remember to declare the jee namespace at the top of your beans file, as described in C.2.3 The jee schema.

Solution 5

Another feature: instead of of server.xml, you can add "Resource" tag in
your_application/META-INF/Context.xml (according to tomcat docs) like this:

<Context>
<Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource"
  username="dbUsername" password="dbPasswd"
  url="jdbc:postgresql://localhost/dbname"
  driverClassName="org.postgresql.Driver"
  initialSize="5" maxWait="5000"
  maxActive="120" maxIdle="5"
  validationQuery="select 1"
  poolPreparedStatements="true"/>
</Context>
Share:
274,397

Related videos on Youtube

Suzan Cioc
Author by

Suzan Cioc

Not to be offended

Updated on January 10, 2020

Comments

  • Suzan Cioc
    Suzan Cioc over 4 years

    It is said that in the Spring javadoc article about DriverManagerDataSource class, that this class is very simple and that 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

    The question is: how do I accomplish this?

    For example, if I wish to have DataSource bean to access my custom MySQL database, what would I require then? What should I write in the context configuration, etc?

  • Étienne Miret
    Étienne Miret over 10 years
    @skaffman Yes, but you provide a link to Spring reference documentation.
  • Pavel Niedoba
    Pavel Niedoba almost 9 years
    what file exactly do you mean by "Tomcat's web context.xml" ?
  • kaliatech
    kaliatech almost 9 years
    @PavelNiedoba Tomcat uses a "context" for tomcat specific web app configuration. The context file and/or context configuration can be placed in various locations, so I can't give you a definitive answer. A common location is "/META-INF/context.xml". See "Defining a context" section here: tomcat.apache.org/tomcat-8.0-doc/config/…
  • Phate
    Phate over 8 years
    Mmm...doesn't seem working for my oracle db, any differences with postgresql?
  • kaliatech
    kaliatech over 8 years
    @Phate There are no fundamental differences with Oracle vs PostgreSQL at the JDBC/JNDI/Tomcat level. However, Oracle is very different from PostgreSQL when it comes to Oracle client/server setup details. Outside scope of original question/answer. Suggest posting a new question with details of what you have tried, specific versions, and any error messages. Example: stackoverflow.com/questions/10388137/…
  • Sajib Acharya
    Sajib Acharya about 8 years
    @kaliatech, hi, I was following a book, Pro Spring 3, and it said that while using the jee namespace we could write: <jee:jndi-lookup jndi-name="java:comp/env/jdbc/databaseName">. I would like to know which approach is better as you are also using an expected-type attribute. Thanks.
  • kaliatech
    kaliatech about 8 years
    @SajibAcharya Using jee namespace or not was mostly a personal preference. Most people thought using the spring XML namespaces were more concise. The expected-type attribute is usually optional, and mostly for safety. If the lookup is not assignable to the given expected-type, a NamingException is thrown. Note that in most newer projects, this style configuration is no longer used. Most newer projects will use JavaConfig per Abdull's answer.
  • ViniciusPires
    ViniciusPires over 7 years
    How does this work with Spring Boot's embedded Tomcat? Where I put these config files?
  • kaliatech
    kaliatech over 7 years
    @ViniciusPires If you are using Spring Boot then you would normally use Spring Boot's built-in support for configuring datasources or JavaConfig style configuration per Abdull's answer. For more information on spring boot's built-in support: docs.spring.io/spring-boot/docs/current/reference/html/…
  • Arend v. Reinersdorff
    Arend v. Reinersdorff over 7 years
    Or use the more specialized JndiDataSourceLookup
  • user3892286
    user3892286 about 7 years
    by this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.
  • Sergio A.
    Sergio A. over 4 years
    by this article, it explain how easy to create a db confguration based on database jndi(db/test) configuration. once you are done with configuration then all the db repositories are loaded using this jndi. I did find useful. If @Pierre has issue with this then let me know. It's complete solution to write db configuration.