如果使用基于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的 默认 数据源资源池设置,有一些属性名称更改。