简体   繁体   中英

Spring Boot properties files using UTF-8

Although Java Properties files traditionally supported only ISO-8859-1, JDK 9 and onward supports properties files encoded in UTF-8 . And while only JDK 9+ supports UTF-8 with built-in default properties file reading, the same technique it uses could be done in any Java version, wrapping around the properties file to add UTF-8 support and fall back to ISO-8859-1 for backwards compatibility (as the JDK implementation does).

I'm new to Spring Boot, and I'm reading about all the nifty properties configurations it brings. Does Spring Boot support loading properties from a properties file encoded in UTF-8? And if not, where in the Spring Boot code is properties file reading consolidated, so that I can add this capability and submit a pull request?

By default Spring only support ISO-8859-1 properties. But there exist several ways to work around this:

  • Use application.yaml property file.
  • Anotate your @Configuration class with @PropertySource(value = "classpath:/custom-name-of-application.properties", encoding="UTF-8")
  • Run your App with the Java Argument to use UTF-8 files: mvn spring-boot:run -Drun.jvmArguments="-Dfile.encoding=UTF-8"

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

use

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

at class level, then you can retrieve the single properties with @value, but you need to define this bean: `

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

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM