Spring配置如何读取多个外部的配置文件(properties文件)和解决乱码问题

Spring配置如何读取多个外部的配置文件(properties文件)和解决乱码问题

如何读取多个外部配置文件

采用XML配置文件读取的方式

在你的maven工程下的spring配置文件,比如我的配置文件在如下目录下:
我的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文件)和解决乱码问题解决!

记得关注和点赞o,还有好多知识点我还没分享哦!只有你的支持,我才能写出更好的分享内容哦,对你是有好处的!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值