簡體   English   中英

使用 UTF-8 的 Spring Boot 屬性文件

[英]Spring Boot properties files using UTF-8

盡管 Java 屬性文件傳統上僅支持 ISO-8859-1,但JDK 9 及更高版本支持以 UTF-8 編碼的屬性文件 雖然只有 JDK 9+ 支持帶有內置默認屬性文件讀取的 UTF-8,但它使用的相同技術可以在任何 Java 版本中完成,環繞屬性文件以添加 UTF-8 支持並回退到 ISO-8859 -1 用於向后兼容(就像 JDK 實現那樣)。

我是 Spring Boot 的新手,我正在閱讀它帶來的所有漂亮的屬性配置。 Spring Boot 是否支持從以 UTF-8 編碼的屬性文件加載屬性? 如果沒有,Spring Boot 代碼中的何處合並了屬性文件讀取,以便我可以添加此功能並提交拉取請求?

默認情況下,Spring 僅支持 ISO-8859-1 屬性。 但是有幾種方法可以解決這個問題:

  • 使用application.yaml屬性文件。
  • 使用@PropertySource(value = "classpath:/custom-name-of-application.properties", encoding="UTF-8")注釋您的 @Configuration 類
  • 使用 Java 參數運行您的應用程序以使用 UTF-8 文件: mvn spring-boot:run -Drun.jvmArguments="-Dfile.encoding=UTF-8"

@PropertySource(value = "classpath:application-${env}.properties", encoding = "UTF-8")

@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")

在類級別,然后您可以使用@value 檢索單個屬性,但您需要定義此 bean:`

@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
    return new PropertySourcesPlaceholderConfigurer();
}
@Value("${my.property1}")
private String property1;

`

暫無
暫無

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

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