问题
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