无法通过Java中的JNDI连接MongoDb [英] Can't connect MongoDb via JNDI in java

查看:126
本文介绍了无法通过Java中的JNDI连接MongoDb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码通过Wildfly中的JNDI连接MongoDB.

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

我在"wildfly-10.1.0.Final/modules/system/layers/base/org/mongodb/main"目录和"mongodb-driver-3.4"中使用mongo-java-driver-3.4.0.jar. "wildfly-10.1.0.Final/standalone/deployments/APPLICATION.war/WEB-INF/lib"中的"0.jar".为什么我会收到上述异常.

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.

推荐答案

使用一个类加载器加载该类时,将获得ClassCastExceptions,然后尝试将其强制转换为另一个类加载器加载的同一个类.

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.

这些类由JVM中的两个不同的Class对象表示,并且强制转换将失败.

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

由于Mongo驱动程序由WildFly提供,请尝试将其与您的应用程序(WAR)捆绑在一起-如果使用Maven,请将驱动程序标记为提供的.

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

这篇关于无法通过Java中的JNDI连接MongoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆