欢迎使用Spring DataSource JNDI Tomcat示例教程。之前我们看到了如何使用Spring JDBC集成实现数据库操作。但是,大多数情况下企业应用程序都部署在一个servlet容器中,例如Tomcat,JBoss等。
目录[ 隐藏 ]
我们知道带有JNDI的DataSource是实现连接池并获得容器实现优势的首选方式。今天我们将看看如何配置Spring Web应用程序以使用Tomcat提供的JNDI连接。
对于我的例子,我将使用MySQL数据库服务器并创建一个包含一些行的简单表。我们将创建一个Spring Rest Web服务,该服务将返回JSON响应,其中包含表中所有数据的列表。
CREATE TABLE `Employee` (
`id` int(11) unsigned NOT NULL,
`name` varchar(20) DEFAULT NULL,
`role` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `Employee` (`id`, `name`, `role`)
VALUES
(1, 'Pankaj', 'CEO'),
(2, 'David', 'Manager');
commit;
在Spring Tool Suite中创建一个Spring MVC项目,以便我们的spring应用程序框架代码准备就绪。一旦我们完成了我们的实现,我们的项目结构将如下图所示。
我们将不得不将Spring JDBC,Jackson和MySQL Database驱动程序添加为pom.xml文件中的依赖项。我的最终pom.xml文件如下所示。
xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.journaldev.springgroupId>
<artifactId>SpringDataSourceartifactId>
<name>SpringDataSourcename>
<packaging>warpackaging>
<version>1.0.0-BUILD-SNAPSHOTversion>
<properties>
<java-version>1.6java-version>
<org.springframework-version>4.0.2.RELEASEorg.springframework-version>
<org.aspectj-version>1.7.4org.aspectj-version>
<org.slf4j-version>1.7.5org.slf4j-version>
<jackson.databind-version>2.2.3jackson.databind-version>
properties>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${org.springframework-version}version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.0.5version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>${jackson.databind-version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${org.springframework-version}version>
<exclusions>
<exclusion>
<groupId>commons-logginggroupId>
<artifactId>commons-loggingartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${org.springframework-version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjrtartifactId>
<version>${org.aspectj-version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-apiartifactId>
<version>${org.slf4j-version}version>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>jcl-over-slf4jartifactId>
<version>${org.slf4j-version}version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>org.slf4jgroupId>
<artifactId>slf4j-log4j12artifactId>
<version>${org.slf4j-version}version>
<scope>runtimescope>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.15version>
<exclusions>
<exclusion>
<groupId>javax.mailgroupId>
<artifactId>mailartifactId>
exclusion>
<exclusion>
<groupId>javax.jmsgroupId>
<artifactId>jmsartifactId>
exclusion>
<exclusion>
<groupId>com.sun.jdmkgroupId>
<artifactId>jmxtoolsartifactId>
exclusion>
<exclusion>
<groupId>com.sun.jmxgroupId>
<artifactId>jmxriartifactId>
exclusion>
exclusions>
<scope>runtimescope>
dependency>
<dependency>
<groupId>javax.injectgroupId>
<artifactId>javax.injectartifactId>
<version>1version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.7version>
<scope>testscope>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-eclipse-pluginartifactId>
<version>2.9version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnatureprojectnature>
additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilderbuildcommand>
additionalBuildcommands>
<downloadSources>truedownloadSources>
<downloadJavadocs>truedownloadJavadocs>
configuration>
plugin>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-compiler-pluginartifactId>
<version>2.5.1version>
<configuration>
<source>1.6source>
<target>1.6target>
<compilerArgument>-Xlint:allcompilerArgument>
<showWarnings>trueshowWarnings>
<showDeprecation>trueshowDeprecation>
configuration>
plugin>
<plugin>
<groupId>org.codehaus.mojogroupId>
<artifactId>exec-maven-pluginartifactId>
<version>1.2.1version>
<configuration>
<mainClass>org.test.int1.MainmainClass>
configuration>
plugin>
plugins>
build>
project>
如果您不熟悉Rest in Spring,请阅读Spring Restful Webservice示例。
我们在Employee表之后建模的Employee bean如下所示。
package com.journaldev.spring.jdbc.model;
import java.io.Serializable;
public class Employee implements Serializable{
private static final long serialVersionUID = -7788619177798333712L;
private int id;
private String name;
private String role;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
我们的简单控制器类如下所示。
package com.journaldev.spring.jdbc.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.journaldev.spring.jdbc.model.Employee;
/**
* Handles requests for the Employee JDBC Service.
*/
@Controller
public class EmployeeController {
private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);
@Autowired
@Qualifier("dbDataSource")
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
@RequestMapping(value = "/rest/emps", method = RequestMethod.GET)
public @ResponseBody List getAllEmployees() {
logger.info("Start getAllEmployees.");
List empList = new ArrayList();
//JDBC Code - Start
String query = "select id, name, role from Employee";
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
List
关于Controller类的重点是:
我们可以通过两种方式查找JNDI并将其连接到Controller DataSource,我的spring bean配置文件包含它们,但其中一个被注释。您可以在这些之间切换,响应也是一样的。
org.springframework.jndi.JndiObjectFactoryBean
通过传递JNDI上下文名称来创建类型的bean 。jndiName是此配置的必需参数。我的spring bean配置文件如下所示。
xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<annotation-driven />
<resources mapping="/resources/**" location="/resources/" />
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
beans:bean>
<beans:bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<beans:property name="messageConverters">
<beans:list>
<beans:ref bean="jsonMessageConverter" />
beans:list>
beans:property>
beans:bean>
<beans:bean id="jsonMessageConverter"
class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
beans:bean>
<beans:bean id="dbDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<beans:property name="jndiName" value="java:comp/env/jdbc/MyLocalDB"/>
beans:bean>
<context:component-scan base-package="com.journaldev.spring.jdbc.controller" />
beans:beans>
现在我们已完成项目,最后一部分是在Tomcat容器中执行JNDI配置以创建JNDI资源。
"jdbc/TestDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource"
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/TestDB"
username="pankaj"
password="pankaj123"
maxActive="100"
maxIdle="20"
minIdle="5"
maxWait="10000"/>
在server.xml文件的GlobalNamingResources部分中添加以上配置。
"jdbc/MyLocalDB"
global="jdbc/TestDB"
auth="Container"
type="javax.sql.DataSource" />
我们还需要创建Resource Link以在我们的应用程序中使用JNDI配置,这是将其添加到服务器context.xml文件中的最佳方式。
请注意,ResourceLink名称应与我们在应用程序中使用的JNDI上下文名称匹配。还要确保tomcat lib目录中存在MySQL jar,否则tomcat将无法创建MySQL数据库连接池。
我们的项目和服务器配置已完成,我们已准备好进行测试。将项目导出为WAR文件并将其放在tomcat部署目录中。
Rest调用的JSON响应如下图所示。
这就是Spring与servlet容器JNDI上下文集成的全部内容,从下面的链接下载示例项目并使用它来了解更多信息。
下载Spring DataSource JNDI项目
转载来源:https://www.journaldev.com/2597/spring-datasource-jndi-with-tomcat-example