Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@PropertySource and UTF-8 properties file

Is it possible, using @PropertySource annotation, to configure the encoding that has to be used to load the property file?

An example to clarify my problem

@Configuration
@PropertySource("classpath:/myprop.properties")
public class MyApplicationContext {

    @Autowired(required = true)
    private Environment env;

    @Bean
    public MyBean myBean() {
       return new MyBean(env.getRequiredProperty("application.name"));
    }

}

myprop.properties is aUTF-8 file but, no matter what, "application.name" is interpreted as ISO-8859-1.

The workaround is to escape special chars in the properties file, but setting the encoding was possible with the old context:property-placeholder so I think it should be possible to do the same with @PropertySource

like image 966
andrea silva Avatar asked Aug 15 '14 11:08

andrea silva


People also ask

What is the difference between UTF 8 and ISO 8859 1?

UTF-8 is a multibyte encoding that can represent any Unicode character. ISO 8859-1 is a single-byte encoding that can represent the first 256 Unicode characters. Both encode ASCII exactly the same way.

What is the use of @PropertySource?

Spring @PropertySource annotation is used to provide properties file to Spring Environment. This annotation is used with @Configuration classes. Spring PropertySource annotation is repeatable, means you can have multiple PropertySource on a Configuration class.

What is ConfigurationProperties?

@ConfigurationProperties allows to map the entire Properties and Yaml files into an object easily. It also allows to validate properties with JSR-303 bean validation. By default, the annotation reads from the application. properties file. The source file can be changed with @PropertySource annotation.


2 Answers

It is now possible:

@PropertySource(value = "classpath:/myprop.properties", encoding="UTF-8")

like image 68
Aidar Makhmutov Avatar answered Sep 18 '22 11:09

Aidar Makhmutov


.properties files are per definition ISO-8859-1 encoded. So I'm afraid you can't do that.

You can however use \uXXXX unicode escapes to represent any unicode character you want. The (slightly misnamed) native2ascii tool can help with automatically doing that.

like image 27
Joachim Sauer Avatar answered Sep 20 '22 11:09

Joachim Sauer