Spring配置如何读取多个外部的配置文件(properties文件)和解决乱码问题
如何读取多个外部配置文件
采用XML配置文件读取的方式
在你的maven工程下的spring配置文件,比如我的配置文件在如下目录下:
在里面进行扫描读取外部配置文件:
读取单个配置文件的情况:(比如要读取jdbc.properties配置文件,我们可以在配置文件中增加下面的语句:)
<context:property-placeholder location="classpath:jdbc.properties/>
读取多个配置文件的情况:
<context:property-placeholder location="classpath:jdbc.properties,classpath:other.properties" />
采用注解的方式读取外部配置文件
因为spring在实际开发使用中,越来愈多的使用注解的方式,所以如何采用注解的方式读取多个外部配置文件呢,如下操作:
读取单个配置文件的情况
@PropertySource(value = "classpath:jdbc.properties")
读取多个配置的情况:
@PropertySources({@PropertySource(value = "classpath:jdbc.properties"),@PropertySource(value = "classpath:other.properties")})
如何解决读取配置文件中存在中文会导致乱码的情况
采用xml的方式
单个文件的情况
增加file-encoding属性
<context:property-placeholder location="classpath:jdbc.properties" file-encoding="utf-8"/>
多个文件的情况
<context:property-placeholder location="classpath:jdbc.properties,classpath:other.properties" file-encoding="utf-8"/>
从上面来看,只需要增加file-encoding这个属性就可以了,指定编码
采用注解的方式
单个文件的情况
增加encoding属性,设置编码为utf-8
@PropertySource(value = "classpath:jdbc.properties",encoding = "utf-8")
多个文件的情况
@PropertySources({@PropertySource(value = "classpath:jdbc.properties",encoding = "utf-8"),@PropertySource(value = "classpath:other.properties",encoding = "utf-8")})
从上面来看,只需要增加encoding这个属性就可以了,指定编码,而且每个文件要单独指定encoding属性,这样更灵活,互不干扰!
至此,Spring配置如何读取多个外部的配置文件(properties文件)和解决乱码问题解决!