簡體   English   中英

Spring Boot默認屬性編碼改變了嗎?

[英]Spring Boot default properties encoding change?

我試圖找到一種方法來為Spring引導中的application.property文件中的@Value注釋訪問的屬性設置UTF-8編碼。 到目前為止,我已經通過創建bean成功地將編碼設置為我自己的屬性源:

@Bean
@Primary
public PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
    PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
    configurer.setLocation(new ClassPathResource("app.properties");
    configurer.setFileEncoding("UTF-8");
    return configurer;
}

這種解決方案存在兩個問題 這一次,它不適用於Spring Boot默認使用的“application.properties”位置( http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config .html #boot-features-external-config ),我被迫使用不同的文件名。

另一個問題是,通過它我可以手動定義和排序多個源的支持位置(例如,在jar與外部jar屬性文件等中),從而重做已經完成的工作。

如何獲取對已配置的PropertySourcesPlaceholderConfigurer的引用,並在應用程序初始化的恰當時間更改其文件編碼?

編輯:也許我在其他地方犯了錯誤? 這就是導致實際問題的原因:當我使用application.properties允許用戶將個人名稱應用於從應用程序發送的電子郵件時:

@Value("${mail.mailerAddress}")
private String mailerAddress;

@Value("${mail.mailerName}")
private String mailerName;                       // Actual property is Święty Mikołaj

private InternetAddress getSender(){
    InternetAddress sender = new InternetAddress();
    sender.setAddress(mailerAddress);
    try {
        sender.setPersonal(mailerName, "UTF-8"); // Result is Święty Mikołaj
        // OR: sender.setPersonal(mailerName);   // Result is ??wiÄ?ty Miko??aj
    } catch (UnsupportedEncodingException e) {
        logger.error("Unsupported encoding used in sender name", e);
    }
    return sender;
}

當我添加了如上所示的placeholderConfigurer bean,並將我的屬性放在'app.properties'中時,它就恢復了。 只需將文件重命名為'application.properties'就可以打破它。

顯然 ,Spring Boot的ConfigFileApplicationListener加載的屬性采用ISO 8859-1字符編碼進行編碼,這是根據設計和格式規范進行的。

另一方面, .yaml格式支持開箱即用的UTF-8。 一個簡單的擴展更改為我解決了這個問題。

@JockX建議完美無缺。 此外,從屬性到yaml的轉換非常簡單。 這個:

spring.main.web_environment=false
email.subject.text=Here goes your subject
email.from.name=From Me
email.from.address=me@here.com
email.replyTo.name=To Him
email.replyTo.address=to@him.com

會成為:

spring:
  main:
    web_environment: false
email:
  subject:
    text: Here goes your subject
  from:
    name: From Me
    address: me@here.com
  replyTo:
    name: To Him
    address: to@him.com

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM