SSM-Spring-Spring装配Bean-加载属性(properties)文件

SSM-Spring-Spring装配Bean-加载属性(properties)文件

​ 使用properties属性文件可以减少硬编码,比如修改环境只需要修改配置文件就可以了,有效提高开发人员的便利性,在Spring中可以通过注解或者XML的方法进行加载属性文件


使用注解的方式加载属性文件

​ Spring 提供注解@PropertySource来加载属性文件,他的配置项:

  1. name:字符串,配置这次属性配置的名称
  2. value:字符串数组,配置多个属性文件
  3. ignoreResourceNotFound:是否开启忽略处理,默认fales
  4. encoding:编码为“”

两种方法获取配置属性:

  1. 通过环境来获取对应的配置属性

在这里插入图片描述

  1. 通过PropertySources PlaceholderConfigurer 类解析属性文件

使用XML方式加载属性文件

在XML配置文件中添加 < context:property-placeholder > 元素加载配置文集即可

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/util  http://www.springframework.org/schema/beans/spring-util.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
	<!-- 配置加载属性文件-->
    <context:property-placeholder location="classpath:jdbc.properties" ignore-resource-not-found="true"/>
</beans>

属性location:配置属性路径的选项,可以配置单个或者多个文件,多文件之间要用逗号隔开

为了可读性,可以采取以下方式设置多配置文件情况

    <bean id="property" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
        <property name="location">
            <value>classpath:jdbc.properties</value>
            <value>classpath:log4j.properties</value>
        </property>
        <property name="ignoreResourceNotFound" value="true"></property>
    </bean>

这样设置可读性更好

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值