如何让IntelliJ自动识别target/generated为生成源根目录?
解决IntelliJ自动识别target/generated为生成源根的方案
方法1:通过Maven Build Helper插件标记源码目录
无需修改CXF XJC插件的输出路径,只需在项目pom.xml中添加build-helper-maven-plugin,将target/generated标记为源码目录,IntelliJ会自动读取Maven配置并识别为生成源根:
<build> <plugins> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>build-helper-maven-plugin</artifactId> <version>3.3.0</version> <executions> <execution> <id>add-source</id> <phase>generate-sources</phase> <goals> <goal>add-source</goal> </goals> <configuration> <sources> <source>target/generated</source> </sources> </configuration> </execution> </executions> </plugin> </plugins> </build>
添加完成后,执行mvn generate-sources或刷新IntelliJ的Maven项目即可生效。如果是多项目架构,可将该配置放到父pom.xml中,所有子项目自动继承,无需逐个修改。
方法2:自定义IntelliJ项目模板(针对新建项目)
若频繁创建此类项目,可通过自定义模板预配置目录规则:
- 打开
File > New > Project from Template,选择现有模板或创建新模板 - 在模板的模块设置中,手动将
target/generated标记为生成源根 - 保存模板,后续新建项目使用该模板时,目录会自动被识别
方法3:IntelliJ全局启动脚本(多项目批量处理)
通过Groovy脚本实现项目打开时自动配置:
- 打开
File > Settings > Tools > Startup Tasks - 添加新的Groovy任务,输入以下脚本:
import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootModificationUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile Project project = project def moduleManager = ModuleManager.getInstance(project) def fs = LocalFileSystem.getInstance() moduleManager.modules.each { module -> def targetGenerated = fs.findFileByPath(module.moduleFilePath.replace(".iml", "") + "/target/generated") if (targetGenerated != null) { ModuleRootModificationUtil.addContentEntry(module, targetGenerated.parent) { entry -> entry.addSourceFolder(targetGenerated, true) // true标记为生成源根 } } }
脚本会在项目打开时自动查找target/generated目录并设置为生成源根,适用于多项目场景,无需逐个手动配置。
内容的提问来源于stack exchange,提问作者tkalvin
相关产品推荐
相关产品推荐

