在Spring中配置properties文件

1、开启命名空间

1.复制xmlns,在后面加上:context,将bean改为context

2.复制两个http,将bean改为context

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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/context
                http://www.springframework.org/schema/context/spring-context.xsd

                ">

2、使用命名空间加载properties配置文件

jbdc.driver=com.mysql.jbdc.Driver
  <!--2、使用命名空间加载properties配置文件-->
    <context:property-placeholder location="jdbc.properties"/>

3、使用属性占位符读取properyies配置文件中的内容

    <!--3、使用属性占位符读取文件properties中的属性-->
    <bean class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jbdc.driver}"/>
    </bean>

注意:配置文件中我们可能会出现与系统环境配置命名相同的情况,此时系统环境优先级高于我们自定义的配置,可能会出现错误

解决方法:关闭系统环境变量

<context:property-placeholder location="jdbc.properties" system-properties-mode="NEVER"/>

4、加载多个配置文件

<context:property-placeholder location="classpath:*.properties" system-properties-mode="NEVER"/>

在classpath后面加上* 表示不仅可以在当前项目中加载配置文件,还可以在依赖的jar包中加载配置文件。

 <context:property-placeholder location="classpath*:*.properties" system-properties-mode="NEVER"/>

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,关于spring配置文件加载properties文件,可以使用以下几种方式: 1. 使用PropertyPlaceholderConfigurer属性占位符 可以在配置文件使用${}占位符来引用属性值,同时需要在配置文件引入对应的*.properties文件。在Spring容器启动时,会通过PropertyPlaceholderConfigurer将properties配置文件的键值对装载到Spring的环境变量,供${}占位符使用。 例如: ``` <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:/config/app.properties</value> </list> </property> </bean> <bean id="user" class="com.example.User"> <property name="name" value="${user.name}"/> <property name="age" value="${user.age}"/> </bean> ``` 在上面的例子,将classpath:/config/app.properties的键值对装载到Spring的环境变量,供${}占位符使用。 2. 使用util命名空间的PropertiesFactoryBean 可以在Spring配置文件使用util命名空间的PropertiesFactoryBean来装载properties文件的属性,并且使用${}占位符引用这些属性值。 例如: ``` <util:properties id="appConfig" location="classpath:/config/app.properties"/> <bean id="user" class="com.example.User"> <property name="name" value="${user.name}" /> <property name="age" value="${user.age}" /> </bean> ``` 在上面的例子,通过util:properties装载classpath:/config/app.properties的属性。在User bean使用${}占位符引用属性值。 希望这些方法能够帮到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值