【MyBatis】MyBatis Tomcat JNDI原理及源码分析

本文介绍了Tomcat JNDI的基本原理和配置步骤,包括导入jar包、配置context.xml以及使用JNDI API获取服务。接着详细阐述了MyBatis如何利用JNDI,解析了源码并提供了配置示例,包括在mybatis-config.xml中的配置和数据源验证方法。
摘要由CSDN通过智能技术生成

一、 Tomcat JNDI

JNDI(java nameing and drectory interface),是一组在Java应用中访问命名和服务的API,所谓命名服务,即将对象和名称联系起来,使得可以通过名称访问并获取对象。

简单原理介绍:点击访问

tomcat已经集成该服务(内置并默认使用DBCP连接池),简单来说就是键值对的mapping,而且在tomcat服务器启动的首页configuration中就已经有完成的示例代码。要想使用tomcat的JNDI服务,只需要导入相关的jar包,建立所需的配置文件,采用JDK的命名服务API根据配置名称即可获得相应的服务。每个步骤的详细解释以及范例如下文所述。

1. jar包导入

tomcat内置了DBCP并默认使用该连接池,在tomcat的lib包中已经DBCP的两个jar包,因此不需要导入,如果使用其他连接池技术,则需要重新拷贝连接池的jar包。拷贝数据库驱动包到tomcat lib目录下,完成jar包的导入。

细节:将所需jar包直接拷贝到tomcat的lib目录中,而不是在应用中build path导入jar包。这是因为JNDI的原理类似于windows的注册表,通过配置文件(context.xml:下节详细介绍)在tomcat启动的时候就告诉tomcat在其命名服务目录下对应着配置文件中的服务名字创建服务应用。这是tomcat对外提供的一个整体服务,而不是单独对某一个应用提供的服务。

2. 配置文件:comtext.xml

在META-INF目录下建立context.xml配置文件,在文件中需要配置资源名字name和资源类型type,建立文件的目的就是告诉服务器根据服务名字创建相应的服务应用。

如下示例(DBCP),服务名称是“jdbc/mybatis-jndi”,对应的服务类型是“javax.sql.DataSource”,即通过Tomcat提供的JNDI服务,根据name=“jdbc/mybatis-jndi”可以获取到type=“javax.sql.DataSource”的服务,至于type中还需要配置什么东西,则根据实际的type类型来进行配置即可。

<?xml version="1.0" encoding="UTF-8"?>
<Context>
    <!-- maxActive: Maximum number of database connections in pool. Make sure 
        you configure your mysqld max_connections large enough to handle all of your 
        db connections. Set to -1 for no limit. -->
    <!-- maxIdle: Maximum number of idle database connections to retain in pool. 
        Set to -1 for no limit. See also the DBCP documentation on this and the minEvictableIdleTimeMillis 
        configuration parameter. -->
    <!-- maxWait: Maximum time to wait for a database connection to become available 
        in ms, in this example 10 seconds. An Exception is thrown if this timeout 
        is exceeded. Set to -1 to wait indefinitely. -->
    <!-- username and password: MySQL username and password for database connections -->
    <!-- driverClassName: Class name for the old mm.mysql JDBC driver is org.gjt.mm.mysql.Driver 
        - we recommend using Connector/J though. Class name for the official MySQL 
        Connector/J driver is com.mysql.jdbc.Driver. -->
    <!-- url: The JDBC connection url for connecting to your MySQL database. -->

    <Resource name="jdbc/mybatis-jndi" auth="Container" type="javax.sql.DataSource"
        maxActive="100" 
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值