Can't connect MongoDb via JNDI in java

我的未来我决定 提交于 2019-12-11 11:57:43

问题


I am trying to connect MongoDB through JNDI in wildfly using the below code.

Context ctx = new InitialContext();
MongoClient mongoClient = (MongoClient) ctx.lookup("java:global/MyMongoClient");

But i am getting the following error.

 Exception->com.mongodb.MongoClient cannot be cast to com.mongodb.MongoClient

I am using mongo-java-driver-3.4.0.jar in "wildfly-10.1.0.Final/modules/system/layers/base/org/mongodb/main" directory and "mongodb-driver-3.4.0.jar" in "wildfly-10.1.0.Final/standalone/deployments/APPLICATION.war/WEB-INF/lib". Why am i getting the above exception.


回答1:


You will get ClassCastExceptions when the class is loaded with one classloader, then try to cast it to the same class loaded by a different classloader.

The classes are represented by two different Class objects inside the JVM and the cast will fail.

Since Mongo-driver is supplied by WildFly, try not bundling it with your application (WAR) - if using Maven, mark the driver as provided.



来源:https://stackoverflow.com/questions/53946210/cant-connect-mongodb-via-jndi-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!