使用Maven开发MongoDB插件时依赖缺失致服务器启动报错
解决Maven打包未包含MongoDB依赖导致的NoClassDefFoundError问题
1. 检查maven-shade-plugin的完整配置
shade插件是打胖包的核心,确保配置绑定到package阶段并正确包含所有依赖。以下是标准有效配置:
<build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>3.5.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <!-- 若插件有主类,替换为你的主类全路径 --> <mainClass>com.your.plugin.YourMainClass</mainClass> <filters> <filter> <artifact>*:*</artifact> <excludes> <!-- 排除签名文件避免打包冲突 --> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> </execution> </executions> </plugin> </plugins> </build>
执行mvn clean package后,找到target目录下带-shaded后缀的Jar包,解压后检查com/mongodb/client/MongoClients.class是否存在。
2. 排除插件间打包冲突
同时配置maven-shade-plugin和maven-assembly-plugin可能导致打包逻辑冲突。优先保留shade插件打胖包,暂时注释assembly插件配置后重新测试。如果必须使用assembly,需确保其descriptor文件明确包含所有依赖:
<assembly xmlns="http://maven.apache.org/ASSEMBLY/2.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/ASSEMBLY/2.1.0 http://maven.apache.org/xsd/assembly-2.1.0.xsd"> <id>fatjar</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <outputDirectory>/</outputDirectory> <useProjectArtifact>true</useProjectArtifact> <unpack>true</unpack> <scope>runtime</scope> </dependencySet> </dependencySets> </assembly>
3. 确认MongoDB依赖的Scope配置
检查pom.xml中mongodb-driver-sync的依赖范围,若设置为provided,Maven会跳过该依赖的打包:
<dependency> <groupId>org.mongodb</groupId> <artifactId>mongodb-driver-sync</artifactId> <version>4.11.1</version> <!-- 使用适配你的项目的版本 --> <!-- 确保没有<scope>provided</scope>配置 --> </dependency>
4. 清理Maven缓存并重新构建
执行以下命令清理本地缓存,强制更新依赖,避免依赖下载不完整的问题:
mvn clean install -U
5. 验证Jar包内容
打包完成后,使用jar tf target/your-plugin-shaded.jar命令列出Jar包内的文件,搜索com/mongodb/client/MongoClients确认是否存在。
内容的提问来源于stack exchange,提问作者Moritz L.
相关产品推荐
相关产品推荐

