使用Wildfly 21 JNDI object-factory在Sping Boot 中连接Mongodb

eh57zj3b  于 2023-08-04  发布在  Go
关注(0)|答案(1)|浏览(124)

我尝试在springboot war应用程序中使用wildfly jndi连接到mongodb,它抛出了以下铸造异常:

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'java:global/MyMongoClient' is expected to be of type 'com.mongodb.client.MongoClient' but was actually of type 'com.mongodb.client.internal.MongoClientImpl'

字符串
Wildfly 21 Standalone.xml对象工厂:

<subsystem xmlns="urn:jboss:domain:naming:2.0">
        <bindings>
            <object-factory name="java:global/MyMongoClient" module="org.mongodb" class="com.mongodb.client.MongoClientFactory">
                <environment>
                    <property name="connectionString" value="mongodb://localhost:27017"/>
                </environment>
            </object-factory>
        </bindings>
        <remote-naming/>
    </subsystem>


Wildfly 21 mongodb模块配置:

<module xmlns="urn:jboss:module:1.3" name="org.mongodb">  
   <resources>  
        <resource-root path="mongodb-driver-sync-4.6.1.jar"/>
        <resource-root path="mongodb-driver-core-4.6.1.jar"/>          
        <resource-root path="bson-4.6.1.jar"/>         
   </resources>  
   <dependencies>  
       <module name="javax.api"/>  
       <module name="javax.transaction.api"/>  
       <module name="javax.servlet.api" optional="true"/>  
   </dependencies>


查找jndi的Java代码:

@Resource(lookup = "java:global/MyMongoClient")
private MongoClient mongoClient;


甚至不使用上下文查找:

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


我甚至尝试使用直接实现的类而不是接口:

@Resource(lookup = "java:global/MyMongoClient")
private MongoClientImpl mongoClient;


还是同样的错误:

org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'java:global/MyMongoClient' is expected to be of type 'com.mongodb.client.internal.MongoClientImpl' but was actually of type 'com.mongodb.client.internal.MongoClientImpl'


我正在使用Sping Boot 2.7.13、Java 11、Wildfly 21、mongo-driver 4.6.1、spring-data-mongodb 3.4.13和mongodb 3.2
你们得想想我错过了什么。

gj3fmq9x

gj3fmq9x1#

经过几天的挠头,发现MongoClient类被多个ClassLoaders加载,因为我在应用程序pom.xml中添加了依赖项,并且在wildfly上也将相同的mongo java驱动程序jar放置在服务器模块上。
通过在pom.xml中进行以下更改修复了此问题:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-war-plugin</artifactId>
      <configuration>
         <archive>
            <manifestEntries>
               <Dependencies>org.mongodb</Dependencies>
            </manifestEntries>
         </archive>
     </configuration>
</plugin>

字符串

相关问题