如何使用Java配置在Tomcat 8中配置JNDI数据源:

如何使用Java配置在Tomcat 8中配置JNDI数据源:,java,spring,jndi,Java,Spring,Jndi,如何在Java配置文件中配置JNDI数据源,而不是在“web.xml”Servlet上下文中配置以下代码段: <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/DatabaseName</res-ref-name> <res-type>javax.sql.DataSource</res-type>

如何在Java配置文件中配置JNDI数据源,而不是在“web.xml”Servlet上下文中配置以下代码段:

<resource-ref>
   <description>DB Connection</description>
   <res-ref-name>jdbc/DatabaseName</res-ref-name>
   <res-type>javax.sql.DataSource</res-type>
   <res-auth>Container</res-auth>
</resource-ref>

数据库连接
jdbc/DatabaseName
javax.sql.DataSource
容器

注意:不要忘记将“mysql-connector-java-5.1.36.jar”复制到主安装文件夹中Tomcat的“lib”子文件夹中

第一:在“pom.xml”文件中添加以下依赖项:


注意:“jdbc/DatabaseName”是我们已经在“context.xml”文件中添加的“name”属性。

要完成SMGs回答:对于xml配置的Spring,我使用以下代码(注意“webapp”配置文件,对于单元测试,您需要一个独立于Web服务器的数据源)


可以通过三个步骤完成:

第1步:

在tomcat conf/server.xml的GlobalNamingResources标记下添加以下条目

  <Resource auth="Container" driverClassName="DB_Drive_class-name" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/MyJNDI" password="&&&&&&&&&&&&&" type="javax.sql.DataSource" url="jdbc:db2://URL:PORT/DBNAME" username="&&&&&&&&&"/>

第二步:

在tomcat conf/context.xml的rootcontext标记下添加以下条目

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

第三步:

web.xml中添加数据源引用

<resource-ref>
 <description>DB2 Datasource</description>
 <res-ref-name>jdbc/MyJNDI</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

DB2数据源
jdbc/MyJNDI
javax.sql.DataSource
容器
注意:这是一个全局Tomcat配置,数据源可以与不同的应用程序共享。

回答如下:回答如下:
<beans profile="webapp">
    <!-- get dataSources from web-container -->
    <bean name="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean" scope="singleton">
        <property name="jndiName" value="java:comp/env/jdbc/DatabaseName" />
        <property name="resourceRef" value="true" />
    </bean>
</beans>
  <Resource auth="Container" driverClassName="DB_Drive_class-name" maxActive="100" maxIdle="30" maxWait="10000" name="jdbc/MyJNDI" password="&&&&&&&&&&&&&" type="javax.sql.DataSource" url="jdbc:db2://URL:PORT/DBNAME" username="&&&&&&&&&"/>
<ResourceLink  name="jdbc/MyJNDI"  global="jdbc/MyJNDI" type="javax.sql.DataSource"/>
<resource-ref>
 <description>DB2 Datasource</description>
 <res-ref-name>jdbc/MyJNDI</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>