PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式
我就廢話不多說了,大家還是直接看代碼吧~
try
{
EncodedResource encodedResource = new EncodedResource(new ClassPathResource(path), Charsets.UTF_8);
Properties properties = PropertiesLoaderUtils.loadProperties(encodedResource);
}
catch (IOException e)
{
LOGGER.info("Champion:read properties failure",e);
}
補充知識:使用Spring PropertyPlaceholderConfigurer 配置中文出現(xiàn)亂碼的解決方法
問題描述
在使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer 讀取配置文件時,發(fā)現(xiàn)對于中文的處理會出現(xiàn)亂碼現(xiàn)象,比如有如下的配置項及其內(nèi)容:
content.shell=#!/bin/bash \necho "test,測試一下!!" \nsleep $1
采用如下的配置方式:
<bean id="propertyConifgurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:evn.properties</value>
</property>
</bean>
通過Spring獲取到的配置項內(nèi)容,中文變成了亂碼。
解決方法
通過了解類org.springframework.beans.factory.config.PropertyPlaceholderConfigurer的繼承關(guān)系,發(fā)現(xiàn)父類org.springframework.core.io.support.PropertiesLoaderSupport中有這樣的屬性fileEncoding,這一屬性的使用是在loadProperties方法中:
/**
* Load properties into the given instance.
* @param props the Properties instance to load into
* @throws IOException in case of I/O errors
* @see #setLocations
*/
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for (Resource location : this.locations) {
if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location);
}
try {
PropertiesLoaderUtils.fillProperties(
props, new EncodedResource(location, this.fileEncoding), this.propertiesPersister);
}
catch (IOException ex) {
if (this.ignoreResourceNotFound) {
if (logger.isWarnEnabled()) {
logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
}
}
else {
throw ex;
}
}
}
}
}
通過添加fileEncoding=utf-8屬性可以解決上述問題:
<bean id="propertyConifgurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:evn.properties</value>
</property>
<property name="fileEncoding">
<value>utf-8</value>
</property>
</bean>
以上這篇PropertiesLoaderUtils 出現(xiàn)中文亂碼的解決方式就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
spring boot 防止重復(fù)提交實現(xiàn)方法詳解
這篇文章主要介紹了spring boot 防止重復(fù)提交實現(xiàn)方法,結(jié)合實例形式詳細分析了spring boot 防止重復(fù)提交具體配置、實現(xiàn)方法及操作注意事項,需要的朋友可以參考下2019-11-11
在controller中如何設(shè)置接收參數(shù)的默認值
這篇文章主要介紹了在controller中如何設(shè)置接收參數(shù)的默認值,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
Java?-jar參數(shù)設(shè)置小結(jié)
本文主要介紹了Java?-jar參數(shù)設(shè)置小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06
Java基于Guava Retrying實現(xiàn)重試功能
這篇文章主要介紹了Java基于Guava Retrying實現(xiàn)重試功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-07-07
SpringBoot 如何實現(xiàn)自定義Redis序列化
這篇文章主要介紹了SpringBoot 如何實現(xiàn)自定義Redis序列化方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10

