如何使用Java配置在Tomcat 8中配置JNDI DataSource: [英] How to Configure JNDI DataSource in Tomcat 8 with Java Configuration:
问题描述
如何在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:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!