09-Spring5 xml引入外部属性文件

1.测试类

  • 要求在xml文件中创建bean, 并通过引入外部属性文件的方式注入属性值.

User 类

package com.limi.test;

public class User {

    private String name;

    private Integer age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

测试类MyTest

package com.limi.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MyTest {

    @Test
    public void test1(){
        //1.加载bean的xml文件, 以src为根目录
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        //2.获取配置的对象, 参数1:bean的id值, 参数2: 类名.class
        User user1 = context.getBean("User", User.class);

        //3.使用对象
        System.out.println("user1:"+user1);
    }
}

2.xml文件的编写

  • 第一步:引入context命名空间
  • 第二步:引入外部属性文件
  • 第三步:引用外部属性文件中的属性值

bean1.xml
在这里插入图片描述

bean1.xml

<?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">
        <!--第一步:引入context命名空间-->
        <!-- 需要修改beans标签, 引入context命名空间, 上面的灰色部分即为新增内容-->

    <!-- 第二步:引入外部属性文件-->
    <!--引入外部属性文件user.properties-->
    <context:property-placeholder location="user.properties"></context:property-placeholder>

    <!--id是唯一标识, class是全类名 -->
    <bean id="User" class="com.limi.test.User">
        <!--第三步:引用外部属性文件中的属性值-->
        <!--使用方法${外部属性名}-->
        <property name="name" value="${user.name}"></property>
        <property name="age" value="${user.age}"></property>
    </bean>
</beans>

在这里插入图片描述

3.测试结果

可以看到成功地通过外部属性文件为bean注入属性值.
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值