BUG情景:项目使用spring的jdbc连连接数据库,同时引用了tomcat连接池。项目使用maven管理jar包,明明已经加入了mysql的依赖,但是就是报找不到mysql driver class 的异常!╮(╯▽╰)╭
spring-datasource.xml
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
<property name="driverClassName" value="${spring.jdbc.driverClassName}"></property>
<property name="url" value="${spring.jdbc.url}"></property>
<property name="username" value="${spring.jdbc.username}"></property>
<property name="password" value="${spring.jdbc.password}"></property>
<property name="validationQuery" value="select 1" />
<property name="testOnBorrow" value="true" />
<property name="testWhileIdle" value="true"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${spring.jdbc.initialSize}" />
<property name="minIdle" value="${spring.jdbc.maxIdle}" />
<property name="maxActive" value="${spring.jdbc.maxActive}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${spring.jdbc.maxWait}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${spring.jdbc.minEvictableIdleTimeMillis}" />
<!-- 杂项 -->
<property name="testOnReturn" value="${spring.jdbc.testOnReturn}" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
Bug原因
参考Stack Overflow上面的这篇回答
原因摘录在此:
There is actually a very simple workaround with Spring. Instead of having the Tomcat connection pool create the database connection and fail because of class loader shenanigans, let Spring create it and pass a reference to the connection pool.
<!-- Data source template for use in the connection pool. -->
<bean id="dataSourceTemplate" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<!-- Connection pool as data source. -->
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<!-- Refer to a separately created bean as a data source template to work around a quirk of Tomcat's class loader. -->
<property name="dataSource" ref="dataSourceTemplate" />
...
</bean>
Then the connection pool will actually use the database connection as a template for creating as many additional connections as it needs.The best part is that you don’t have to mess with tomcat/lib, which you may not even have access to.