我一直使用Spring的依赖注入来获取数据源对象,并在我的DAO中使用它们,但是现在,我必须编写一个没有该对象的应用程序。
使用Spring,我可以编写如下内容:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1/app?characterEncoding=UTF-8" /> <property name="username" value="u" /> <property name="password" value="p" /> </bean>
但是,如何在没有Spring或其他任何东西的情况下在DAO中使用数据源?我仅使用servlet和JSP。性能是非常重要的因素。
信不信由你,人们在Spring之前就编写了应用程序,但有些人仍然没有使用它:)在您的情况下,您可以使用Tomcat连接池(并且在文档中有 MySQL的完整配置示例)。让我总结一下:
首先,将驱动程序放入$CATALINA_HOME/lib。
$CATALINA_HOME/lib
然后,通过在Context中添加资源声明来在Tomcat中配置JNDI数据源:
<Context path="/DBTest" docBase="DBTest" debug="5" reloadable="true" crossContext="true"> <!-- maxActive: Maximum number of dB 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 dB 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 dB 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 dB username and password for dB 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 dB. --> <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" username="javauser" password="javadude" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/javatest"/> </Context>
在您的中声明此资源web.xml:
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4"> <description>MySQL Test App</description> <resource-ref> <description>DB Connection</description> <res-ref-name>jdbc/TestDB</res-ref-name> <res-type>javax.sql.DataSource</res-type> <res-auth>Container</res-auth> </resource-ref> </web-app>
并在您的应用程序中通过JNDI查找获得数据源:
Context initCtx = new InitialContext(); Context envCtx = (Context) initCtx.lookup("java:comp/env"); DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB"); Connection conn = ds.getConnection(); ... use this connection to access the database ... conn.close();
请注意,此类lookup代码通常以形式编码ServiceLocator(当您无法使用DI容器或框架为您注入代码时)。
lookup
ServiceLocator