Spring读取外部properties配置文件

前言Spring提供了读取外部properties文件的机制,可以使用读取到的数据为bean的属性赋值实现步骤准备外部properties文件开启context命名空间的支持Spring配置文件的头部配置要添加以下配置:xmlns:context="http://www.springframework.org/schema/context"http://www.springframework.org/schema/contexthttps://www.springframework.
摘要由CSDN通过智能技术生成

前言

Spring提供了读取外部properties文件的机制,可以使用读取到的数据为bean的属性赋值

实现步骤

  1. 准备外部properties文件

  2. 开启context命名空间的支持

    Spring配置文件的头部配置要添加以下配置:

    xmlns:context="http://www.springframework.org/schema/context"

    http://www.springframework.org/schema/context

    https://www.springframework.org/schema/context/spring-context.xsd

  3. 加载指定的properties文件

    <context:property-placeholder location="classpath:db.properties"/>

  4. 使用获取到的数据

    <property name="username" value="${user}"/>

  5. 注意

    • 如果要加载所有的properties文件,使用*.properties表示加载所有后缀名为properties的文件。
    • 读取数据使用${propertiesName},其中propertiesName指properties文件中的属性名。

使用实例

  • PropertiesDemo.java

    public class PropertiesDemo {
         
    
        private String username;
        private String password;
    
        public void setUsername(String username) {
         
            this.username = username;
        }
    
        public 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值