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>

这样设置可读性更好

猜你喜欢

转载自blog.csdn.net/weixin_43958223/article/details/115177240