我试图找到一种方法来为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'就会破坏它 .
2 回答
由Spring Boot的
ConfigFileApplicationListener
加载的Apparently属性采用ISO 8859-1字符编码进行编码,这是根据设计并根据格式规范进行的 .另一方面,.yaml format支持开箱即用的UTF-8 . 一个简单的扩展更改为我解决了这个问题 .
@JockX建议完美无缺 . 此外,从属性到yaml的转换非常简单 . 这个:
会成为: