如何解决Swagger星号导入未被Spotless清理的问题?
解决Swagger生成星号导入及Spotless无法清理的问题
方案一:阻止Swagger生成星号导入
Swagger Codegen(或OpenAPI Generator)可通过配置参数控制导入样式,避免生成通配符导入:
- 若使用OpenAPI Generator Maven插件,在配置中添加
useSingleImport参数,或通过importMappings明确指定需要导入的具体类:<plugin> <groupId>org.openapitools</groupId> <artifactId>openapi-generator-maven-plugin</artifactId> <version>6.6.0</version> <executions> <execution> <goals> <goal>generate</goal> </goals> <configuration> <!-- 其他必填配置:API spec路径、输出目录等 --> <configOptions> <!-- 强制生成单个类导入而非通配符 --> <useSingleImport>true</useSingleImport> <!-- 针对验证约束类的明确映射,确保生成具体导入 --> <importMappings>NotNull=javax.validation.constraints.NotNull,Size=javax.validation.constraints.Size</importMappings> </configOptions> </configuration> </execution> </executions> </plugin> - 说明:
useSingleImport会全局禁用通配符导入;importMappings可针对特定包下的类做精确控制,避免Swagger自动生成*导入。
方案二:配置Spotless处理未使用的星号导入
Spotless原生的removeUnusedImports不处理通配符导入,但可结合格式化器先将通配符转为具体导入,再清理未使用的:
修改Spotless配置,添加google-java-format或Eclipse JDT格式化器:
<plugin> <groupId>com.diffplug.spotless</groupId> <artifactId>spotless-maven-plugin</artifactId> <version>2.36.0</version> <configuration> <java> <includes> <include>target/somewhere/**</include> </includes> <importOrder/> <removeUnusedImports/> <!-- 引入google-java-format,自动将通配符导入转为具体类导入 --> <googleJavaFormat> <version>1.15.0</version> <aosp>false</aosp> </googleJavaFormat> <!-- 也可使用Eclipse JDT格式化器,需确保配置开启导入转换 --> <!-- <eclipseJdt> <version>4.26.0</version> <configFile>${project.basedir}/eclipse-formatter.xml</configFile> </eclipseJdt> --> </java> </configuration> <executions> <execution> <goals> <goal>apply</goal> </goals> <phase>compile</phase> </execution> </executions> </plugin>
- 说明:google-java-format会自动解析代码中实际使用的类,将
import javax.validation.constraints.*;替换为import javax.validation.constraints.NotNull;这类具体导入,之后Spotless的removeUnusedImports就能清理掉未使用的导入项。
补充:IntelliJ批量处理(临时方案)
若上述自动化方案暂时无法生效,可通过IntelliJ批量处理:
- 选中目标目录
target/somewhere; - 右键选择
Optimize Imports; - 在弹窗中勾选
Use single class imports和Remove unused imports,点击Run即可完成批量优化。
内容的提问来源于stack exchange,提问作者HowToTellAChild
相关产品推荐
相关产品推荐

