您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

spring如何使用Tomcat提供的JNDI数据源?

spring如何使用Tomcat提供的JNDI数据源?

如果使用基于Spring XML架构的配置,请在Spring上下文中进行如下设置:

<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" />

或者,使用以下简单的bean配置进行设置:

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

您可以使用以下类似方法在tomcat的server.xml中声明JNDI资源:

<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>

并从Tomcat的web context.xml中引用JNDI资源,如下所示:

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

参考文档:

编辑:此答案已针对Tomcat 8和Spring 4进行了更新。对于Tomcat的 数据源资源池设置,有一些属性名称更改。

Java 2022/1/1 18:13:58 有394人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶