如何在application.yml文件中指定spring.mandatory-file-encoding为UTF-8?
你遇到的这个问题很典型——当你设置了spring.mandatory-file-encoding=UTF-8后,Spring Boot会校验系统的file.encoding属性是否和配置一致,不一致就会直接终止启动。从报错信息能看到,你的JVM当前用的是Cp1252编码,和要求的UTF-8不匹配,所以触发了这个校验错误。
先看看你收到的具体错误提示:
Type=ERROR,Category=org.springframework.boot.context.FileEncodingApplicationListener,Thread=main,MDC=,Text=System property 'file.encoding' 目前为'Cp1252',应与'spring.mandatoryFileEncoding'中定义的'UTF-8'一致
Type=ERROR,Category=org.springframework.boot.context.FileEncodingApplicationListener,Thread=main,MDC=,Text=环境变量LANG为'en_US.UTF-8',可使用与编码'UTF-8'匹配的区域设置
Type=ERROR,Category=org.springframework.boot.context.FileEncodingApplicationListener,Thread=main,MDC=,Text=环境变量LC_ALL为'null',可使用与编码'UTF-8'匹配的区域设置
另外,这个监听器的官方作用说明是:
FileEncodingApplicationListener:如果系统文件编码与环境中设置的预期值不匹配,将终止应用启动。默认无作用,但如果将{@code spring.mandatory_file_encoding}设置为字符编码名称(例如"UTF-8"),当系统属性与其不相等时,该初始化器将抛出异常。
核心原因
file.encoding是JVM启动时就初始化的系统属性,Spring Boot的spring.mandatory-file-encoding只是做校验用的,根本没法修改这个系统属性。所以你需要直接给JVM添加-Dfile.encoding=UTF-8参数,让JVM从启动那一刻就用UTF-8编码。
具体解决方法
根据你的运行环境,选对应的方式设置JVM参数:
IDE中运行(比如IntelliJ IDEA/Eclipse)
打开项目的运行配置(Run/Debug Configurations),在VM options里添加:-Dfile.encoding=UTF-8,保存后重启应用就行。命令行启动Jar包
启动时直接带上参数:java -Dfile.encoding=UTF-8 -jar your-app.jarMaven构建启动
在pom.xml的spring-boot-maven-plugin中添加JVM参数:<plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments> </configuration> </plugin>然后用
mvn spring-boot:run启动项目。Gradle构建启动
在build.gradle中添加:bootRun { jvmArgs = ["-Dfile.encoding=UTF-8"] }然后用
./gradlew bootRun启动。全局设置(系统环境变量)
- Linux/macOS:在
~/.bashrc或~/.zshrc中添加export JAVA_OPTS="-Dfile.encoding=UTF-8",执行source ~/.bashrc生效。 - Windows:在系统环境变量中新增
JAVA_OPTS,值设为-Dfile.encoding=UTF-8,重启命令行或IDE后生效。
- Linux/macOS:在
额外说明
如果你的环境变量LC_ALL是null,可以考虑把它设置为en_US.UTF-8(和LANG保持一致),这能辅助JVM识别正确的编码,但核心还是要设置JVM的file.encoding参数才行。
内容的提问来源于stack exchange,提问作者Alisha Raju

