Spring p名称空间注入和c名称空间注入

P代表propertory 属性, 是set注入的简化方式 (提供set方法)

C代表Constructor 构造注入的简化方式 (提供构造方法)

package com.itheima.di;

import java.util.Date;

/**
 * set注入 ,必须要有set方法
 *
 */
public class Person {
    private int id;
    private String name;
    private int age;
    private Date birthday;

    public Person() {
    }

    public Person(int id, String name, int age, Date birthday) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:c="http://www.springframework.org/schema/c"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

 <bean id="birthday" class="java.util.Date"></bean>
    <!--使用p名称空间注入属性-->
    <bean id="person_p" class="com.itheima.di.Person" p:id="3" p:userName="杨过" p:age="22" p:birthday-ref="birthday"/>

    <!--使用c名称空间注入-->
    <bean id="person_c" class="com.itheima.di.Person" c:id="3" c:name="雕" c:age="220" c:birthday-ref="birthday"/>

</beans>
//测试p名称空间注入
    @Test
    public void testPerson_P(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("personbean.xml");
        Person person = context.getBean("person_p", Person.class);
        System.out.println(person);
    }


    //测试c名称空间注入
    @Test
    public void testPerson_C(){
        ApplicationContext context =
                new ClassPathXmlApplicationContext("personbean.xml");
        Person person = context.getBean("person_c", Person.class);
        System.out.println(person);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值