spring学习笔记(三):通过 IOC 创建 有参构造 的对象

带参数构造器的实体类 User.java:

package com.spring.demo;

/**
 * 实体类 javabean
 */
public class User {
    private int id;
    private String name;

    public User(int id, String name) {
        System.out.println("User 对象创建:有参构造");
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

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

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

配置文件 bean.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:p="http://www.springframework.org/schema/p"
       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">

    <!-- 创建 带有参构造 的对象 -->
    <bean id="user" class="com.spring.demo.User">
        <!--
            指定有参构造的 参数:
                value:参数值
                index:参数索引,0表示第一个参数,1表示第二个参数
                type:参数的类型
                ref:引用外部的对象数据
        -->
        <constructor-arg value="22" index="0" type="int"/>
        <constructor-arg value="张三" index="1" type="java.lang.String"/>
    </bean>

</beans>

测试程序 Demo.java:

public class Demo {
    @Test
    public void test1() {
        // 创建 IOC 容器
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");

        // 从 IOC 容器中获取 对象
        User user = (User) context.getBean("user");
        System.out.println(user);
    }
}

输出结果:

 

 

配置 <constructor-arg> 节点的时候有一个属性 ref,表示引用外部的对象。

修改 bean.xml 如下:

再次运行测试程序 结果为:

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值