spring1-test3-通过构造器为bean的属性赋值(index,type属性介绍),通过p名称为bean赋值

测试1:使用有参构造器进行赋值调用。直接调用有参的构造方法为属性赋值,不会再去调用set方法为属性赋值了。和之前无参的构造方法为属性赋值的方法不一样,注意

<bean id="person3" class="Person">
    <constructor-arg name="name" value="小明"></constructor-arg>
    <constructor-arg name="age" value=""></constructor-arg>
    <constructor-arg name="email" value="xiaoming@jiajia.com"></constructor-arg>
    <constructor-arg name="gender" value="男"></constructor-arg>
</bean>
@Test
public void test03(){
    /**
     * 调用有参构造器为属性赋值
     */
    ApplicationContext ioc = new ClassPathXmlApplicationContext("spring-config.xml");
    Object bean3 = ioc.getBean("person3");
    System.out.println(bean3);
}

直接写value,不写name属性,那么就要严格按照构造器参数的位置来.

<bean id="person4" class="Person">
    <constructor-arg value="小花"></constructor-arg>
    <constructor-arg value="67"></constructor-arg>
    <constructor-arg value="女"></constructor-arg>
    <constructor-arg value="xiaohau@qq.com"></constructor-arg>
</bean>

也可以通过index来指定构造器中参数的位置,索引是从0开始的,你可以和上面正规的比较下。

<bean id="person4" class="Person">
    <constructor-arg value="小花"></constructor-arg>
    <constructor-arg value="女" index="2"></constructor-arg>
    <constructor-arg value="67" index="1"></constructor-arg>
    <constructor-arg value="xiaohau@qq.com" index="4"></constructor-arg>
</bean>
  • 注意:当构造器重载时,使用index会出现问题。这个时候可以使用type

测试2:通过p名称空间为bean赋值

  1. 首先要添加p的名称空间到这个项目中去,xml的配置文件也需要写。
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
<!-- 通过p名称空间为bean赋值,导入p名称空间 -->
<!-- 名称空间:在xml中名称空间是用来防止标签重复的 -->
<!--
    <book>
        <b:name>西游记</b:name>
        <price>19.98</price>
        <author>
            <a:name>吴承恩</a:name>
            <gender>男</gender>
        </author>
    </book>
    带前缀的标签<c:forEach> <jsp:forward>
   -->
  1. 使用,在配置文件中写
<bean id="person06" class="Person"
      p:name="haha" p:age="18" p:email="haha@haha.com" p:gender="男">
</bean>
  1. 之后就可以在测试类中使用了。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值