繁体   English   中英

Spring Boot默认属性编码改变了吗?

[英]Spring Boot default properties encoding change?

我试图找到一种方法来为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'就可以打破它。

显然 ,Spring Boot的ConfigFileApplicationListener加载的属性采用ISO 8859-1字符编码进行编码,这是根据设计和格式规范进行的。

另一方面, .yaml格式支持开箱即用的UTF-8。 一个简单的扩展更改为我解决了这个问题。

@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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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