Tomcat的JDBC数据源之一(如何使用配置JDBC数据源)

84 阅读2分钟

JDBC数据源是什么:

许多 Web 应用程序需要通过 JDBC 驱动程序访问数据库,以支持该应用程序所需的功能。Java EE 平台规范要求 Java EE 应用服务器为此目的提供DataSource实现(即用于 JDBC 连接的连接池)。

注意- Tomcat 中的默认数据源是DBCP 2连接池 。但是,可以通过编写自己的自定义资源工厂 来使用任何其他实现的连接池。

如何使用JDBC数据源:

  1. 安装JDBC驱动,将驱动程序的 JAR 文件安装到 $CATALINA_HOME/lib目录中。
  2. 声明你的资源需求 修 改 Web 应用程序下 ( /WEB-INF/web.xml) 声明 JNDI 名称,后续通过该名称查找预配置的数据源。示例代码:
<resource-ref>
  <description>
   对 java.sql.Connection 实例的工厂的资源引用,可用于与 Web 应用程序的 <Context> 配置中配置的特定数据库进行通信。
  </description>
  <res-ref-name>
    jdbc/TestDB
  </res-ref-name>
  <res-type>
    javax.sql.DataSource
  </res-type>
  <res-auth>
    Container
  </res-auth>
</resource-ref>

3.配置Tomcat的资源,将jdbc的配置加入应用程序的[<Context>]Web元素中。代码示例:

<Context ...>
  ...
  <Resource name="jdbc/TestDB"
            auth="Container"
            type="javax.sql.DataSource"
            username="dbusername"
            password="dbpassword"
            driverClassName="com.mysql.cj.jdbc.Driver"
            url="jdbc:mysql://mysqlUrl:mysqlPort/databaseName"
            maxTotal="8"
            maxIdle="4"/>
  ...
</Context>

4.如何在代码中使用该数据源。代码示例如下:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource)envCtx.lookup("jdbc/TestDB");

Connection conn = ds.getConnection();
... 使用此连接访问数据库 ...
conn.close();

自此tomcat的数据源配置完成。

如果默认的数据源不满足的你的需求,tomcat支持自定义数据源。那么如何自定义呢?下面分四个步骤讲解。

如何使用自定义数据源

  1. 编写你的自定义资源工厂类。

需要实现JNDI  javax.naming.spi.ObjectFactory接口的类。每次Web 应用程序调用lookup()绑定到该工厂的上下文条目时, getObjectInstance()都会调用该方法。示例代码:

public class MyBeanFactory implements ObjectFactory {

  public Object getObjectInstance(Object obj,
      Name name2, Context nameCtx, Hashtable environment)
      throws NamingException {

      // 获取我们指定的bean类的一个实例
      MyBean bean = new MyBean();

      // 从我们的属性中自定义 bean 属性
      Reference ref = (Reference) obj;
      Enumeration addrs = ref.getAll();
      while (addrs.hasMoreElements()) {
          RefAddr addr = (RefAddr) addrs.nextElement();
          String name = addr.getType();
          String value = (String) addr.getContent();
          if (name.equals("foo")) {
              bean.setFoo(value);
          } else if (name.equals("bar")) {
              try {
                  bean.setBar(Integer.parseInt(value));
              } catch (NumberFormatException e) {
                  throw new NamingException("Invalid 'bar' value " + value);
              }
          }
      }

      // 返回自定义实例
      return (bean);

  }

}

在这个例子中,无条件地创建一个类的新实例,并根据包含在 配置这个工厂com.mycompany.MyBean的元素中的参数填充它的属性。

2.声明你的资源需求

修 改 Web 应用程序下 ( /WEB-INF/web.xml) 声明 JNDI 名称。后续通过该名称查找此 bean 的新实例。最简单的方法是使用<resource-env-ref>元素,如下所示:

<resource-env-ref>
<description>
MyBean 实例的对象工厂。
</description>
<resource-env-ref-name>
 MyBeanFactory
</resource-env-ref-name>
<resource-env-ref-type>
 com.mycompany.MyBean
</resource-env-ref-type>
</resource-env-ref>

3.配置Tomcat的资源工厂

将以下 [<Context>]元素添加到 Web 应用程序中:

<Context ...>
  ...
  <Resource name="MyBeanFactory" auth="Container"
            type="com.mycompany.MyBean"
            factory="com.mycompany.MyBeanFactory"
            singleton="false"
            bar="23"/>
  ...
</Context>

4.在你的应用程序中使用该资源

示例代码如下:

Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
MyBean bean = (MyBean) envCtx.lookup("MyBeanFactory");

writer.println("foo = " + bean.getFoo() + ", bar = " +
               bean.getBar());

如何在tomcat中使用JDBC数据源就结束了。下一章将从源码分析,tomcat是如何加载jdbc数据源的。