英文:
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 代码中的属性文件读取是在哪里合并的,以便我可以添加这个功能并提交一个拉取请求?
英文:
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?
答案1
得分: 5
默认情况下,Spring 只支持 ISO-8859-1 属性。但是有几种方法可以解决这个问题:
- 使用
application.yaml
属性文件。 - 在您的 @Configuration 类上使用
@PropertySource(value = "classpath:/custom-name-of-application.properties", encoding="UTF-8")
注解。 - 使用 Java 参数运行您的应用以使用 UTF-8 文件:
mvn spring-boot:run -Drun.jvmArguments="-Dfile.encoding=UTF-8"
。
英文:
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"
答案2
得分: 1
@PropertySource(value = "classpath:application-${env}.properties", encoding = "UTF-8")
英文:
@PropertySource(value = "classpath:application-${env}.properties", encoding = "UTF-8")
答案3
得分: 0
在类级别上使用以下代码:
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
然后,你可以使用 @Value
来获取单个属性,但是你需要定义以下 bean:
@Bean
public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
return new PropertySourcesPlaceholderConfigurer();
}
@Value("${my.property1}")
private String property1;
英文:
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;
`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论