目錄
1、Spring 使用@Value 讀取.properties文件中文亂碼
2.3、不設置編碼格式,編寫文件時將中文轉化爲unicode編碼
1、Spring 使用@Value 讀取.properties文件中文亂碼
最近在整理SpringBoot相關的學習示例,準備針對多環境不同配置進行整理。發現一個問題,我使用的 *.properties 文件。在寫單元測試用例的時候,發現從.properties文件之中讀取的文件未亂碼;導致單元測試不成功。
在Spring中常常使用.properties對一些屬性進行一些基本的配置, Spring 在讀取*.properties文件時,默認使用的是ascii碼, 這時 我們需要對其編碼進行轉換.
2、針對*.properties編碼轉換的幾種方法彙集
2.1、在配置spring.xml文件時,聲明所需的∗.properties文件時直接使用"utf−8"編碼
此種方法目前估計很少人使用啦,此方法在Spring xml配置時代可以使用
<context:property-placeholder location="classpath:*.properties" file-encoding="UTF-8"/>
2.2、針對所需類上注入可使用以下方式來聲明編碼格式
@Component
@PropertySource(value = "classpath:themeConfig.properties",encoding = "utf-8")
public class ThemeStyleConfig {
@Value("${clolor}")
private String clolor;
@Value("${themeName}")
private String themeName;
}
2.3、不設置編碼格式,編寫文件時將中文轉化爲unicode編碼
曾經寫過Java代碼讀取 文件,需要設置讀取文件的格式編碼
/**
* properties 轉換內容轉換爲Excel
*/
private void propertiesFileConvertToExcel(String inputPropertieFilePath,String outExcelFileNamePath) {
System.setProperty("file.encoding", "UTF-8");
readPropertiesContent(inputPropertieFilePath);
writePropertiesContentToExcelFile(outExcelFileNamePath);
}
/**
* Excel寫回到Properties文件之中
* @param propertiesPath
*/
public void writeExcelToPropertiesFile(String propertiesPath) {
Properties props = new OrderedProperties();
//創建一個文件對象,該對象將指向屬性文件的位置
File propertiesFile = new File(propertiesPath);
try {
//通過傳遞上述屬性文件創建FileOutputStream 並且設置每次覆蓋重寫
FileOutputStream xlsFos = new FileOutputStream(propertiesFile,false);
// 首先將哈希映射鍵轉換爲Set,然後對其進行迭代。
Iterator<String> mapIterator = excelContentToPropertiesMap.keySet().iterator();
//遍歷迭代器屬性
while(mapIterator.hasNext()) {
// extracting keys and values based on the keys
String key = mapIterator.next().toString();
String value = excelContentToPropertiesMap.get(key);
String keys = "Keys";
if(!keys.equals(key)) {
//在上面創建的props對象中設置每個屬性key與value
props.setProperty(key, value);
}
}
//最後將屬性存儲到實屬性文件中。
props.store(new OutputStreamWriter(xlsFos, "utf-8"), null);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
並且最近使用Maven的一個插件也遇到類似問題。
這個其實是 maven-resources-plugins 搞得鬼,無論如何修改編碼都不行。最後沒轍了,只好把中文強制修改爲 unicode,雖然不利用閱讀,但是解決了問題。
問題地址:maven filter 中文亂碼,應該用什麼思路解決?
2.4、使用IntelliJIDEA 如下圖操作即可解決
3、Spring <context:property-placeholder/> 屬性說明
<context:property-placeholder
location="屬性文件,多個之間逗號分隔"
file-encoding="文件編碼"
ignore-resource-not-found="是否忽略找不到的屬性文件"
ignore-unresolvable="是否忽略解析不到的屬性,如果不忽略,找不到將拋出異常"
properties-ref="本地Properties配置"
local-override="是否本地覆蓋模式,即如果true,那麼properties-ref的屬性將覆蓋location加載的屬性,否則相反"
system-properties-mode="系統屬性模式,默認ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永遠不用ENVIRONMENT的,OVERRIDE類似於ENVIRONMENT"
order="順序"
/>