IDEA maven加载依赖失败不展示Dependencies项
使用低版本maven时(3.6.3及以下),用IDEA非模板的方式手动新建maven工程,有时候会遇到丢失Dependencies的情况,maven模块仅展示一个Lifecycle项,很多情况下是因为主目录maven pom配置异常导致。
错误示例如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.3.3</version></parent><groupId>com.xxx</groupId><artifactId>xxx-xxx</artifactId><version>1.0.0</version><name>xxx-xxx-ai</name><packaging>pom</packaging><description>XXX</description><modules><module>xxx-api</module><module>xxx-xxx</module></modules><properties><maven.compiler.source>21</maven.compiler.source><maven.compiler.target>21</maven.compiler.target><java.version>21</java.version><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding></properties><dependencyManagement><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-dependencies</artifactId><version>2023.0.1</version><type>pom</type><scope>import</scope></dependency>……其他配置</dependencyManagement>……其他配置
</project>
现象就是,当某个操作或手动操作触发工程reimport时,丢失Dependencies栏,仅展示标红部分(Plugins和Dependencies都缺失)。同时可能伴随很多类提示查找依赖类失败,大量import报红。
‘
网上一堆解决方案,根本不通用,甚至连问题原因都解释不清楚,或者也没有解释如何定位问题引导解决办法。
这里有一个快速提示异常的办法是,升级maven插件,例如使用3.9.11替换低版本的maven 3.6.3,注意使用相同setting和本地库,规避重新下载大量依赖文件。
这时候重新reload工程,控制台就回提示你具体的问题所在。
例如这里就是因为上述主目录pom.xml中,有一个依赖缺乏版本号。
<dependencyManagement><dependencies> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></dependency>......</dependencies>
</dependencyManagement>
理论上,由于继承父级依赖中的引用,所以子模块中可以直接引用这个依赖,而不需要还在<dependencyManagement>标签中定义无版本引用,这是报错的根本原因。
在<dependencyManagement>标签中的无<version>标签的dependency,都当加上版本号,或者直接移除这些无版本号定义的<dependency>,重新reload即可解决问题。如果依旧未出现Dependencies项,可能由于idea的本地.idea配置未及时自动刷新的原因,则考虑替换高版本后,reimport,然后换为低版本maven即可。
究其根本,其实是maven的pom文件配置规范,<dependencyManagement>标签中管理子模块的统一依赖版本,必须明确定义其中的各<dependency>版本号。