2015-01-10 108 views
3

我试图找到一种方法来设置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'即可将其分解。

+1

在这之前,你肯定没有简单的解决方案?我使用环境变量,并且使用了UTF-8的application.properties,没有任何特别的问题。你遇到的问题究竟是什么? –

+0

@AlessandroSantini我已经更新了它对我造成的特殊问题。 – JockX

+0

如果您调试该类,您是否看到错误?这听起来更像是一个输出问题。 – chrylis

回答

6

Apparently Spring Boot的ConfigFileApplicationListener加载的属性以ISO 8859-1字符编码进行编码,这是通过设计并根据格式规范编码的。

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

0

@JockX建议完美。另外,从属性到yaml的转换非常简单。 此:

spring.main.web_environment=false 
email.subject.text=Here goes your subject 
email.from.name=From Me 
[email protected] 
email.replyTo.name=To Him 
[email protected] 

将成为:

spring: 
    main: 
    web_environment: false 
email: 
    subject: 
    text: Here goes your subject 
    from: 
    name: From Me 
    address: [email protected] 
    replyTo: 
    name: To Him 
    address: [email protected]