我试图找到一种方法来为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(http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config)默认使用的“application.properties”位置,我不得不使用不同的文件名。
另一个问题是,通过它,我可以手动定义和排序多个源的支持位置(例如,在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'就可以打破它。
答案 0 :(得分:6)
ConfigFileApplicationListener
加载的Apparently属性采用ISO 8859-1字符编码进行编码,这是根据设计并根据格式规范进行的。
另一方面,.yaml format支持开箱即用的UTF-8。一个简单的扩展更改为我解决了这个问题。
答案 1 :(得分:0)
@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
答案 2 :(得分:0)
另一种方法是将完整的文件从.properties
重命名为.yml
,而不是选择需要UTF-8
支持的道具并将其移至.yml
文件。这样,您无需重写您的.properties
文件。
我建议这样做,因为如果您有类似道具
my.string.format= %s-hello-%s
这会破坏.yml文件。您必须将它们写为
my.string.format: |
%s-hello-%s
当在Java代码中读取时,这会导致在属性valye my.string.format
中添加新行。