ctx.lookup()强制转换成DruidDataSource失败

发布于 2021-12-04 03:24:56 字数 5405 浏览 768 评论 5

 新手小白最近尝试JNDI+MYSQL+Druid

但是在获取到DataSource时候强制转换成DruidDataSource会出现异常。

报异常的工具类:

package com.angus.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.alibaba.druid.pool.DruidDataSource;
import com.sun.xml.internal.txw2.IllegalAnnotationException;

public class DBPoolConnection {
	private static DBPoolConnection databasePool = null;
	private static DruidDataSource dds = null;
	//MySQL数据库配置的JNDI数据源连接名,java:comp/env是必须加的,后面跟的是DataSource名
	private static final String MYSQL_DB_JNDINAME = "java:comp/env/jdbc/MysqlDataSource";
	
	public DBPoolConnection() {}
	public static synchronized DBPoolConnection getInstance(){
		if(databasePool==null){
			databasePool = new DBPoolConnection();
		}
		return databasePool;
	}
	
	static{
		try {
			Context ctx = new InitialContext();
			//下面会报一个强制转换失败的异常
			dds= (DruidDataSource)ctx.lookup(MYSQL_DB_JNDINAME);
			
		} catch (NamingException e) {
			e.printStackTrace();
		}
	}
	
	public Connection getMySqlConnection() throws SQLException{
		return dds.getConnection();
	}
	
	public void colse(Connection conn,PreparedStatement pstat,ResultSet rs){
		if(rs!= null){
			try {
				rs.close();
			} catch (SQLException e) {
				throw new IllegalAnnotationException("rs关闭失败");
			}
		}
		
		if(pstat!= null){
			try {
				pstat.close();
			} catch (SQLException e) {
				throw new IllegalAnnotationException("pstat关闭失败");
			}
		}
		 
		if(conn!=null){
			try {
				conn.close();
			} catch (SQLException e) {
				throw new IllegalAnnotationException("conn关闭失败");
			}
		}
	}
	public void colse(Connection conn,PreparedStatement pstat){
		colse(conn, pstat,null);
	}
	public void colse(Connection conn){
		colse(conn, null,null);
	}
}

配置文件:context.xml文件内容

<context>
	<Resource 
		name="jdbc/MysqlDataSource"
		factory="com.alibaba.druid.pool.DruidDataSourceFactory"
        auth="Container"        
        type="javax.sql.DataSource"
        driverClassName="com.mysql.jdbc.Driver"
		url="jdbc:mysql://localhost:3306/news?characterEncoding=utf8;useSSL=true"
		username="root"
		password="sa1234"
		filters="stat"
		initialSize="2"
		maxActive="300"
		maxWait="60000"
		timeBetweenEvictionRunsMillis="60000"
		minEvictableIdleTimeMillis="300000"
		validationQuery="SELECT 1"
		testWhileIdle="true"
		testOnBorrow="false"
		testOnReturn="false"
		poolPreparedStatements="false"
		maxPoolPreparedStatementPerConnectionSize="200"
	
	/>
	
</context>

异常信息:

org.apache.tomcat.dbcp.dbcp2.BasicDataSource@15679a6d
二月 21, 2017 8:39:37 上午 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet [com.angus.servlet.FindUser] in context with path [/TestDruid] threw exception [Servlet execution threw an exception] with root cause
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp2.BasicDataSource cannot be cast to com.alibaba.druid.pool.DruidDataSource
	at com.angus.util.DBPoolConnection.<clinit>(DBPoolConnection.java:34)
	at com.angus.daoImpl.UserDaoImpl.findUser(UserDaoImpl.java:20)
	at com.angus.servlet.FindUser.doPost(FindUser.java:53)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
	at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
	at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:474)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
	at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:624)
	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
	at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:495)
	at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
	at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:767)
	at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1347)
	at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
	at java.lang.Thread.run(Unknown Source)

 

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

泛滥成性 2021-12-06 11:38:07

这样啊,请问有什么好的解决方式没?谢谢

各自安好 2021-12-06 08:14:42

DataSource的提供类DPCP和Druid 他俩虽然都直接或间接实现了java.sql.DataSource ,但是他俩是两个不同的分支,不能强转的~~

清风夜微凉 2021-12-06 07:47:56

嗯,这或许是个很好的解决方法。不过,这样的话我就不知道我目前哪里出了错误。

怎言笑 2021-12-06 02:11:13

回复
按照druid的套路走,看文档

凯凯我们等你回来 2021-12-04 09:25:40

交给spring管理吧

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文