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)文章
springboot druid數(shù)據(jù)庫配置密碼加密的實現(xiàn)
Druid是阿里開發(fā)的數(shù)據(jù)庫連接池,本文主要介紹了springboot druid數(shù)據(jù)庫配置密碼加密的實現(xiàn),具有一定的參考價值,感興趣的可以了解一下2024-06-06
這么設(shè)置IDEA中的Maven,再也不用擔(dān)心依賴下載失敗了
今天給大家?guī)硪粋€IDEA中Maven設(shè)置的小技巧.這個技巧可以說非常有用,學(xué)會設(shè)置之后,再也不用擔(dān)心maven依賴下載變慢的問題,需要的朋友可以參考下2021-05-05
spring-security關(guān)閉登錄框的實現(xiàn)示例
這篇文章主要介紹了spring-security關(guān)閉登錄框的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
基于spring+quartz的分布式定時任務(wù)框架實現(xiàn)
在Spring中的定時任務(wù)功能,最好的辦法當(dāng)然是使用Quartz來實現(xiàn)。這篇文章主要介紹了基于spring+quartz的分布式定時任務(wù)框架實現(xiàn),有興趣的可以了解一下。2017-01-01

