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 prob
It is now possible:
@PropertySource(value = "classpath:/myprop.properties", encoding="UTF-8")
my solution:
new MyBean(new String(env.getProperty("application.name").getBytes("ISO-8859-1"), "UTF-8"));
Or you can use the PropertiesFactoryBean that have the setEncoding method. Here an example from one of my projects
@Bean
public PropertiesFactoryBean cvlExternalProperties() {
PropertiesFactoryBean res = new PropertiesFactoryBean();
res.setFileEncoding("UTF-8");
res.setLocation(new ClassPathResource("conf/external-test.properties"));
return res;
}
and then you can use in the project with the following notation
@Value("#{cvlExternalProperties['myProperty']}")
private String p;
.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.
the old
context:property-placeholder
so I think it should be possible to do the same with@PropertySource
@PropertySource
and context:property-placeholder
are two completely different components. @PropertySource
registers a .properties
file with the ApplicationContext
and Environment
loading the @Configuration
class, while context:property-placeholder
registers a PropertyPlaceholderConfigurer
or PropertySourcesPlaceholderConfigurer
bean to perform placeholder resolution. This bean will have access to the the properties in the .properties
files declared with it and to the properties available to the containing Environment
.
There's nothing you can do about the encoding used for @PropertySource
. It will use the system default.
You can always declare a PropertySourcesPlaceholderConfigurer
bean yourself (with a static
@Bean
method), declare some .properties
files and an encoding. Note, however, that these properties won't be available through the Environment
.
Warm reminder:
define @PropertySource with different features in other project classes can give you results that you're not expected.
for example
In Class A:
@PropertySource(value = "classpath:/myprop.properties", encoding="UTF-8")
While in Class B:
@PropertySource(value = "classpath:/myprop.properties")
Class B's annotation may override Class A's, and in this case Class A's encoding is voided.