Spring读取properties文件出现乱码的解决方法

本文详细介绍了在使用Spring框架时,如何配置applicationContext.xml文件来解决从UTF-8编码的properties资源文件中读取中文时出现的乱码问题。通过设置context:property-placeholder标签的file-encoding属性为UTF-8,可以有效避免乱码现象。

在Spring的applicationContext.xml文件中设置和读取properties资源文件时,如果properties文件是UTF-8编码的,并且需要读取的内容包含中文,那么采取默认的property-placeholder标签配置,则读取属性时便会出现乱码!

通过度娘找到很多相似的问题,但几乎都只有一个解决办法,就是使用jdk自带的native2ascii.exe工具,将properties文件中的中文变为编码的形式,若采用这种办法,那么properties文件几乎是没有可读性的!

查阅Spring的官方手册(spring-framework-reference.pdf),发现配置文件中的context:property-placeholder标签对应的是PropertyPlaceholderConfigurer类,再去查Spring的javadoc-api,发现这个类中有一个setFileEncoding方法,可以设置读取properties文件的编码格式,有戏啊!那么context:property-placeholder标签中有没有对应的attribute可以设置呢?再次查阅applicationContext.xml文件针对context:property-placeholder标签的xsd校验文件(spring-context-4.0.xsd),发现propertyPlaceholder元素有个file-encoding属性,于是乎马上用到配置文件中,乱码问题终于解决了!


也就是将原来的:

<context:property-placeholder location="classpath:*.properties"/>

修改为:

<context:property-placeholder location="classpath:*.properties" file-encoding="UTF-8"/>


<think>我们之前已经详细讨论了Spring Boot properties文件中文乱码解决方案,现在用户再次提出相同问题,可能是希望获得更简洁的总结或不同的方法。不过根据要求,我们需要按照格式回答并给出代码示例。 回顾问题:Spring Boot的properties文件中文乱码解决方法。 以下提供最常用且有效的解决方案: 1. 确保IDE设置正确(以IntelliJ IDEA为例): - 打开File -> Settings -> Editor -> File Encodings - 将Global Encoding、Project Encoding、Default encoding for properties files都设置为UTF-8 - 并勾选“Transparent native-to-ascii conversion” 2. 使用YAML格式代替properties文件(推荐): - YAML原生支持UTF-8,无需转义。 3. 使用Unicode转义序列: - 将中文字符转换为Unicode转义序列,例如“你好”转换为`\u4f60\u597d`。 4. 在配置类中指定编码(适用于自定义properties文件): ```java @Configuration @PropertySource(value = "classpath:custom.properties", encoding = "UTF-8") public class CustomConfig { // ... } ``` 5. 在Spring Boot启动时设置系统属性: ```bash java -Dfile.encoding=UTF-8 -jar your_application.jar ``` 下面重点演示第3种和第4种方法: **方法3:使用Unicode转义序列** 例如,在application.properties中: ```properties greeting=\u4F60\u597D\uFF0C\u4E16\u754C # 表示“你好,世界” ``` 转换工具可以使用JDK自带的`native2ascii`命令,或者在线工具。 **方法4:使用@PropertySource指定编码(针对自定义properties文件)** 注意:Spring Boot默认的application.properties不支持通过@PropertySource指定编码,此方法适用于自定义的properties文件。 步骤: 1. 创建自定义配置文件(如custom.properties)放在src/main/resources下,内容使用UTF-8编码: ```properties custom.greeting=你好,世界 ``` 2. 创建配置类: ```java @Configuration @PropertySource(value = "classpath:custom.properties", encoding = "UTF-8") public class CustomPropertiesConfig { @Value("${custom.greeting}") private String greeting; // 如果需要,可以在这里使用greeting,或者通过@Autowired在其他类中使用 } ``` 3. 注意:如果使用Spring Boot 2.1以下版本,可能还需要自定义PropertySourceFactory: ```java public class Utf8PropertySourceFactory extends DefaultPropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { if (resource == null) { return super.createPropertySource(name, resource); } return new ResourcePropertySource(name, resource.getResource(), resource.getEncoding()); } } ``` 然后在@PropertySource中指定factory: ```java @PropertySource(value = "classpath:custom.properties", encoding = "UTF-8", factory = Utf8PropertySourceFactory.class) ``` **重要提示**:对于Spring Boot默认的application.properties,最佳实践是使用YAML(application.yml)格式,避免乱码问题。 如果用户坚持使用properties文件,且包含中文,那么必须确保IDE设置正确(特别是勾选Transparent native-to-ascii conversion),这样IDEA会自动将中文转为Unicode转义序列。 下面给出一个完整的示例,演示如何在Spring Boot中读取自定义UTF-8编码的properties文件: 1. 创建自定义配置文件:src/main/resources/messages.properties 内容(UTF-8编码): ``` welcome.text=欢迎来到Spring Boot的世界! ``` 2. 创建配置类: ```java @Configuration @PropertySource(value = "classpath:messages.properties", encoding = "UTF-8", factory = Utf8PropertySourceFactory.class) public class MessageConfig { @Autowired private Environment env; @PostConstruct public void init() { System.out.println(env.getProperty("welcome.text")); } } ``` 3. 自定义PropertySourceFactory(如上所述,用于确保使用UTF-8读取): ```java import org.springframework.core.env.PropertySource; import org.springframework.core.io.support.EncodedResource; import org.springframework.core.io.support.PropertySourceFactory; import org.springframework.core.io.support.ResourcePropertySource; import java.io.IOException; public class Utf8PropertySourceFactory implements PropertySourceFactory { @Override public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException { return (name != null ? new ResourcePropertySource(name, resource.getResource(), resource.getEncoding()) : new ResourcePropertySource(resource.getResource(), resource.getEncoding())); } } ``` 这样,在启动应用时,控制台将正确打印中文。 总结:对于非application.properties的自定义properties文件,使用@PropertySource并配合自定义的PropertySourceFactory可以解决中文乱码问题。对于主配置文件,建议转换为YAML格式。 最后,再次强调,统一编码为UTF-8是解决此类问题的根本。 §§相关问题§§: 1. Spring Boot 如何支持多语言国际化(i18n)? 2. 在 Spring Boot 中如何动态刷新配置(不重启应用)? 3. Spring Boot 的 YAML 配置有哪些优点? 4. 如何将 Spring Boot 应用程序打包为可执行的 JAR 文件?</think>### 解决 Spring Boot Properties 文件中文乱码问题 在 Spring Boot 中解决 properties 文件中文乱码问题,核心是确保文件编码与处理编码一致。以下是五种解决方案,按推荐度排序: #### 最佳方案:使用 YAML 格式(推荐) ```yaml # application.yml app: name: "Spring Boot应用" welcome: "你好,欢迎使用本系统!" # 直接支持中文 ``` **优势**: - YAML 原生支持 UTF-8 编码 - 无需特殊配置 - 支持多行文本和结构化数据 #### 方案二:IDE 配置透明转换 (IntelliJ) 1. 打开设置:`File > Settings > Editor > File Encodings` 2. 设置: - Global Encoding: **UTF-8** - Project Encoding: **UTF-8** - Properties Files: **UTF-8** ✅ 勾选 `Transparent native-to-ascii conversion` ![编码设置](https://i.imgur.com/8XJzZQl.png) #### 方案三:Unicode 转义序列 ```properties # application.properties welcome.message=\u4F60\u597D\uFF0C\u6B22\u8FCE\u4F7F\u7528\u672C\u7CFB\u7EDF ``` **转换方法**: 1. 使用 JDK 工具: ```bash native2ascii -encoding UTF-8 input.txt output.properties ``` 2. 在线转换工具:[https://www.zhangxinxu.com/tool/native2ascii/](https://www.zhangxinxu.com/tool/native2ascii/) #### 方案四:启动参数强制编码 ```bash java -Dfile.encoding=UTF-8 -jar your-app.jar ``` #### 方案五:自定义属性加载(高级) ```java @Configuration public class CustomPropertyLoader { @Bean public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() { PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); // 创建支持UTF-8的Properties实例 Properties properties = new Properties(); try (InputStream input = new ClassPathResource("custom.properties").getInputStream()) { // 显式指定UTF-8编码读取 properties.load(new InputStreamReader(input, StandardCharsets.UTF_8)); } catch (IOException e) { throw new RuntimeException("加载配置文件失败", e); } // 设置自定义属性源 configurer.setProperties(properties); return configurer; } } ``` ### 验证解决方案 创建测试 Controller: ```java @RestController public class ConfigController { @Value("${welcome.message}") private String welcomeMsg; @GetMapping("/msg") public String getMessage() { return welcomeMsg; // 访问 /msg 查看输出 } } ``` ### 永久解决方案 1. **在项目中添加编码配置文件**: ```editorconfig # .editorconfig [*.{properties,yml}] charset = utf-8 ``` 2. **Maven 全局编码配置**: ```xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> ``` 3. **Gradle 配置**: ```gradle tasks.withType(JavaCompile) { options.encoding = "UTF-8" } ``` ### 最佳实践总结 | 方案 | 适用场景 | 复杂度 | 维护性 | |------|----------|--------|--------| | YAML 格式 | 新项目/简单配置 | ★☆☆ | ★★★★★ | | IDE 透明转换 | 开发环境 | ★★☆ | ★★★★☆ | | Unicode 转义 | 必须用 properties 文件 | ★★★☆ | ★★★☆☆ | | 启动参数 | 临时解决方案 | ★☆☆ | ★★☆☆☆ | | 自定义加载器 | 复杂企业应用 | ★★★★ | ★★★★☆ |
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值