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="[email protected]"></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="[email protected]"></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="[email protected]" 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="[email protected]" p:gender="男">
</bean>
  1. 之后就可以在测试类中使用了。
发布了52 篇原创文章 · 获赞 1 · 访问量 2262

猜你喜欢

转载自blog.csdn.net/Shen_R/article/details/104883430