如何使用Java配置在Tomcat 8中配置JNDI DataSource:

编程入门 行业动态 更新时间:2024-10-13 10:28:59
本文介绍了如何使用Java配置在Tomcat 8中配置JNDI DataSource:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在Java配置文件中配置JNDI数据源,而不是在web.xmlServlet上下文中跟随代码片段:

How to Configure JNDI DataSource in Java Configuration File Instead of Following Code Snippet in "web.xml" Servlet Context:

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

推荐答案

注意:不要忘记复制mysql -connector-java-5.1.36.jar进入主安装文件夹中的Tomcat的lib子文件夹。

Note: Don't Forget to Copy the "mysql-connector-java-5.1.36.jar" Into Tomcat's "lib" Subfolder in Main Installation Folder.

首先:在pom.xml文件中添加以下依赖项:

First: Add following Dependency in Your "pom.xml" File:

<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency>

第二:在webapp根文件夹中创建META-INF文件夹和context.xml文件以下图片:

Second: Create META-INF Folder and "context.xml" File in "webapp" Root Folder Like the Following Picture:

第三步:在上下文中添加以下代码片段 .xml文件:

Third: Add the Following Code Snippet in "context.xml" File:

<?xml version='1.0' encoding='utf-8'?> <Context> <Resource name="jdbc/DatabaseName" auth="Container" type="javax.sql.DataSource" maxActive="50" maxIdle="30" maxWait="10000" username="DatabaseUsername" password="DatabasePasssword" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/DatabaseName"/> </Context>

第四:在Spring上下文配置文件中创建以下Bean:

Fourth: Create the Following Bean in Spring Context Configuration File:

@Bean public DataSource dataSource() { JndiDataSourceLookup dataSource = new JndiDataSourceLookup(); dataSource.setResourceRef(true); return dataSource.getDataSource("jdbc/DatabaseName"); }

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

Note: "jdbc/DatabaseName" is "name" Attribute that We Added Already in "context.xml" File.

更多推荐

如何使用Java配置在Tomcat 8中配置JNDI DataSource:

本文发布于:2023-10-26 18:25:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530980.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   Java   Tomcat   JNDI   DataSource

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!