I am trying to find a way to set UTF-8 encoding for properties accessed via @Value
annotation from application.property files in Spring boot. So far I have been successfully set encoding to my own properties sources by creating a bean:
@Bean
@Primary
public PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
configurer.setLocation(new ClassPathResource("app.properties");
configurer.setFileEncoding("UTF-8");
return configurer;
}
Such solution presents two problems. For once, it does NOT work with "application.properties" locations used by default by Spring Boot (http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config), and I am forced to use different file names.
And the other problem is, with it I am left with manually defining and ordering supported locations for multiple sources (eg. in jar vs outside jar properties file, etc) thus redoing a job well done already.
How would I obtain a reference to already configured PropertySourcesPlaceholderConfigurer and change it's file encoding at just the right time of application initialization?
Edit:
Perhaps I am doing a mistake somewhere else? This is what causes actual problem for me: When I use application.properties to allow users to apply personal name to emails sent from an application:
@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;
}
When I have placeholderConfigurer
bean as shown above added, and place my property inside 'app.properties' it is resoved just fine. Just renaming the file to 'application.properties' breaks it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…