MapStruct @ValueMapping生成代码非英文编码错误,求设置编码方法
MapStruct生成代码含非英文字符时编码错误问题
我有一个基于Spring Boot的应用,使用MapStruct工具。尝试通过@ValueMapping注解将String类型映射为枚举类型,但String中的非英文字符在生成的代码里出现编码错误。
POM配置
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>11</source> <target>11</target> <forceJavacCompilerUse>true</forceJavacCompilerUse> <annotationProcessorPaths> <path> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-processor</artifactId> <version>1.5.2.Final</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.24</version> </path> <path> <groupId>org.projectlombok</groupId> <artifactId>lombok-mapstruct-binding</artifactId> <version>0.2.0</version> </path> </annotationProcessorPaths> <compilerArgs> <arg> -Amapstruct.defaultComponentModel=spring </arg> </compilerArgs> </configuration> </plugin>
代码示例
@Mapper public interface TestMapper { @ValueMapping(source = "Menschenwürde", target = "TEST_VALUE") TestEnum map(String value); }
生成的错误代码
@Generated( value = "org.mapstruct.ap.MappingProcessor", date = "2022-09-02T18:22:58+0200", comments = "version: 1.5.2.Final, compiler: Eclipse JDT (IDE) 3.21.0.v20200304-1404, environment: Java 11.0.8 (Oracle Corporation)" ) @Component public class TestMapperImpl implements TestMapper { @Override public TestEnum map(String value) { if ( value == null ) { return null; } TestEnum testEnum; switch ( value ) { case "Menschenw�rde": testEnum = TestEnum.TEST_VALUE; break; case "TEST_VALUE": testEnum = TestEnum.TEST_VALUE; break; default: throw new IllegalArgumentException( "Unexpected enum constant: " + value ); } return testEnum; } }
排查情况
TestMapper类已在Spring Tool Suite 4中以UTF-8编码保存- POM中
${project.build.sourceEncoding}变量值为UTF-8 - 命令行执行Maven Build时,生成代码编码正确
- Spring Tool Suite 4中执行Maven Build时,生成代码编码正确
- 但在Spring Tool Suite 4中执行clean build时,生成代码出现编码错误
- 查阅过MapStruct相关编码问题的issue,未找到有效解决方案
- 尝试过Eclipse全局UTF-8设置(内容类型、工作区编码),均未生效
问题
是否有办法设置MapStruct生成代码的编码格式?
解决方案
- 指定编译器编码参数
在Maven编译器插件的compilerArgs中添加编码参数,强制编译器使用UTF-8处理注解处理器生成的代码:
<compilerArgs> <arg>-Amapstruct.defaultComponentModel=spring</arg> <arg>-encoding</arg> <arg>UTF-8</arg> </compilerArgs>
配置项目注解处理器编码
在Spring Tool Suite 4中为项目单独设置注解处理器编码:- 右键项目 → Properties → Java Compiler → Annotation Processing → 勾选"Enable project specific settings"
- 在"Processor Options"中添加
-encoding UTF-8 - 同时在项目的"Resource"设置中,确保"Text file encoding"为UTF-8
改用Maven作为唯一构建工具
在STS中取消IDE内置Java构建器,仅保留Maven构建器:- 右键项目 → Properties → Builders → 取消勾选"Java Builder",只保留"Maven Builder"
- 所有构建操作将通过Maven执行,规避Eclipse JDT的编码问题
内容的提问来源于stack exchange,提问作者dur
相关产品推荐
相关产品推荐

