我试图找到一种方法来设置UTF-8编码的属性,通过@Value
注释从Spring.apprent.property文件访问Spring引导。到目前为止,我已经通过创建一个bean被成功设置编码到我自己的属性来源:Spring Boot默认属性编码更改?
@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 vs 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
豆如上图所示加入,并把我的财产在'app.properties'内部,它被重新设置好了。只需将该文件重命名为'application.properties'即可将其分解。
在这之前,你肯定没有简单的解决方案?我使用环境变量,并且使用了UTF-8的application.properties,没有任何特别的问题。你遇到的问题究竟是什么? –
@AlessandroSantini我已经更新了它对我造成的特殊问题。 – JockX
如果您调试该类,您是否看到错误?这听起来更像是一个输出问题。 – chrylis