我就廢話不多說了,大家還是直接看代碼吧~
1
2
3
4
5
6
7
8
9
10
11
|
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
采用如下的配置方式:
1
2
3
4
5
|
<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方法中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
/** * 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屬性可以解決上述問題:
1
2
3
4
5
6
7
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)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/ppwwp/article/details/106032712