@PropertySource and UTF-8 properties file

Is it possible, using annotation @PropertySource

, to customize the encoding that should be used to load the properties 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 a file UTF-8

, but no matter what "application.name" is interpreted as ISO-8859-1

.

The workaround is to avoid special characters in the properties file, but setting the encoding is possible with the old one context:property-placeholder

, so I think it should be possible to do the same with@PropertySource

+3


source to share


5 answers


It is now possible:



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

+9


source


.properties

files for the definition of ISO-8859-1 encoded. Therefore, I am afraid that you cannot do this.



However, you can use \uXXXX

unicode escapes to represent any unicode character you want. The tool native2ascii

can help with automatically doing this.

+4


source


old context:property-placeholder

, so I think it should be possible to do the same with@PropertySource

@PropertySource

and context:property-placeholder

- two completely different components. @PropertySource

registers a file .properties

with ApplicationContext

and Environment

loading the class @Configuration

, and context:property-placeholder

registers PropertyPlaceholderConfigurer

or PropertySourcesPlaceholderConfigurer

bean to do placeholder resolution. This bean will have access to properties in files declared with it .properties

and properties available to the containing Environment

.

There is nothing you can do about the encoding used for @PropertySource

. It will use the default system.

You can always declare the PropertySourcesPlaceholderConfigurer

bean yourself (using a method static

@Bean

), declare some files .properties

and encoding. Note, however, that these properties will not be available through Environment

.

+3


source


my decision:

new MyBean (new line (env.getProperty ("application.name"). getBytes ("ISO-8859-1"), "UTF-8"));

+1


source


Or you can use PropertiesFactoryBean which has setEncoding method. Here is 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 the following notation in your project

@Value("#{cvlExternalProperties['myProperty']}")
private String p;

      

0


source







All Articles