开始直接使用Spring通过JNDI获取在Tomcat容器中配置的数据源,Tomcat默认的应该是DBCP连接池,没问题,一切OK,由于Hibernate和Spring都推荐使用C3P0连接池,所以就尝试配置一下,没想到整了半下午,才搞定配置,惭愧!网上的内容眼花缭乱,鱼龙混杂,不如自己靠谱!直接上代码,后面附出现的问题!
配置两个地方:
1.Tomcat\conf下的context.xml
2.Spring的配置文件
提示:
1.如果要优化连接池的性能,要对参数进行设置,具体的要看官网!官网最靠谱!官网是王道!
C3P0:http://www.mchange.com/projects/c3p0/
DBCP:http://commons.apache.org/proper/commons-dbcp/
2.C3P0的jar包要放在WEB-INF\lib中,也要放到Tomcat\lib包中
3.通过JNDI配置可以使项目与不同数据库的配置达到解耦的目的
context.xml
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | <!-- DBCP连接池 -->    <Resourcename="jdbc/gdDB"auth="Container"type="javax.sql.DataSource"    username="scott"password="tiger"driverClassName="oracle.jdbc.driver.OracleDriver"    url="jdbc:oracle:thin:@localhost:1521:orcl"    testOnBorrow="true"    testOnReturn="true"    testWhileIdle="true"    validationQuery="SELECT COUNT(*) FROM DUAL"    maxIdle="30"    maxWait="5000"    maxActive="100"    initialSize="10"/>                                                                                                                                                                                                                                              <!-- C3P0连接池 -->    <Resourcename="jdbc/DB"auth="Container"    user="scott"password="tiger"driverClass="oracle.jdbc.driver.OracleDriver"    jdbcUrl="jdbc:oracle:thin:@localhost:1521:orcl"    maxPoolSize="30"    minPoolSize="1"    initialPoolSize="5"    acquireIncrement="2"    idleConnectionTestPeriod="60"    maxIdleTime="60"    factory="org.apache.naming.factory.BeanFactory"    type="com.mchange.v2.c3p0.ComboPooledDataSource"/> | 
applicationContext.xml
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | <!-- 配置JNDI数据源 -->   <beanid="dataSource"       class="org.springframework.jndi.JndiObjectFactoryBean">       <propertyname="jndiName">          <!--  <value>java:comp/env/jdbc/c3p0DB</value> -->          <value>java:comp/env/jdbc/DB</value>       </property>   </bean>   <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">       <propertyname="dataSource">           <refbean="dataSource"/>       </property>   </bean> | 
出现的问题:
1.javax.naming.NamingException: No set method found for property: username
解决方法:
context.xml中,C3P0连接池的配置参数不正确,开始直接Copy上面的DBCP的配置,后来发现DBCP与C3P0的参数名字是不一样的,包括大小写一定要注意!
2.org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type ‘com.mchange.v2.c3p0.mbean.C3P0PooledDataSource‘ to
required type ‘javax.sql.DataSource‘ for property ‘dataSource‘
解决方法:
context.xml中,C3P0连接池的type值配置错误,配置成type="com.mchange.v2.c3p0.ComboPooledDataSource"就OK了!
其它问题就记不太清了!能用就好,有时间再研究优化配置及内部实现原理!
另:发现网上好多贴子说,要配置三处,还有一处是web.xml,但我可检测不需要配置web.xml文件,难道我错了吗?如果有朋友有好的见解,欢迎交流指正,互相学习!
Spring通过JNDI获取在Tomcat容器中配置的C3P0数据源,布布扣,bubuko.com
Spring通过JNDI获取在Tomcat容器中配置的C3P0数据源
原文:http://www.cnblogs.com/xiyubaiyang/p/3783951.html