据说在Spring javadoc关于DriverManagerDataSource
类的文章中,这个类很简单,值得推荐
to use a JNDI DataSource provided by the container. Such a
DataSource
can be exposed as aDataSource
bean in a Spring ApplicationContext viaJndiObjectFactoryBean
问题是:我该如何做到这一点?
例如,如果我希望使用 DataSource
bean 来访问我的自定义 MySQL 数据库,那么我需要什么?上下文配置等应该写什么?
最佳答案
如果使用 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 JNDI Datasource HOW-TO
- Tomcat 8 Context Resource Links Reference
- Spring 4 JEE JNDI Lookup XML Schema Reference
- Spring 4 JndiObjectFactoryBean Javadoc
编辑:此答案已针对 Tomcat 8 和 Spring 4 进行了更新。Tomcat 的 default 数据源资源池设置的属性名称发生了一些变化。
关于java - Spring中如何使用Tomcat提供的JNDI DataSource?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183321/