@PropertySource和UTF-8属性文件 [英] @PropertySource and UTF-8 properties file
问题描述
是否可以使用 @PropertySource
注释来配置加载属性文件时必须使用的编码?
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 是一个
UTF-8
文件,但无论什么,application.name解释为 8859-1
。
myprop.properties
is aUTF-8
file but, no matter what, "application.name" is interpreted as ISO-8859-1
.
解决方法是在属性文件中转义特殊字符,但是可以使用旧的 context:property-placeholder
所以我认为应该可以用 @PropertySource
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
推荐答案
旧的
上下文:property-placeholder
可能对@PropertySource
@PropertySource
和上下文:property-placeholder
是两个完全不同的组件。 @PropertySource
使用 ApplicationContext
注册 .properties
环境
加载 @Configuration
类,而 context:property-placeholder
注册 PropertyPlaceholderConfigurer
或 PropertySourcesPlaceholderConfigurer
bean执行占位符解析。这个bean将访问 .properties
文件中声明的属性以及包含 Environment
。
@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
.
您无法对 @PropertySource
使用的编码做任何事。它将使用系统默认值。
There's nothing you can do about the encoding used for @PropertySource
. It will use the system default.
您可以随时自行声明一个 PropertySourcesPlaceholderConfigurer
bean( static
@Bean
方法),声明一些 .properties
文件和编码。但请注意,这些属性将不能通过环境
。
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
.
这篇关于@PropertySource和UTF-8属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!