第三篇文章:xml方式下给对象的属性赋值的两种方法(setter注入和构造方法注入)

(1)普通类型注入  value注入

有一个类Student:

public class Student
{
    private String name;
}
//注意:使用setter注入(1)需要有相应的set方法的,比如setName,setAge方法
//                    (2)需要有无参的构造方法
//这里为了简化,没有写这个类的setName方法和无参构造方法

在beans.xml文件中:(创建一个Student对象,并且给它的name这个属性赋值)

//new一个对象叫作student,它来自Student类    
<bean id="student"  class="com.kuang.pojo.Student">
       
       //给这个对象student的name属性赋值
       <property name="name"  value="欧阳水鸣"></property>
</bean>

 测试:

      //创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");

        //拿到这个叫做hello的bean
        Student student= (Student) context.getBean("student");

        System.out.println(student.getName());

(2)引用类型注入  ref注入

此时属性是一个对象,也就是说,一个类的对象是另一个类的属性

step1:先创建一个类B

public class B
{
    private int  height;
}

step2:再创建一个类A,类B的对象b是类A的属性

public class A
{
    private B b;
}

//完整的话这里也应该有set方法和无参构造方法:
public class A
{
    private B b;

   //set方法
    public void setB(B  b)
    {
       this.b=b;
    }
 
    //无参构造方法
    public  void  A
    {
      system.out.println("类A的无参构造方法.......");
    }
}

step3:beans.xml这个文件中进行创建对象,给对象赋值

    //创建三个B类的对象b1,b2,b3
    <bean id="b1"  class="com.kuang.pojo.B">
        <property name="height"  value="123"></property>
    </bean>

    <bean id="b2"  class="com.kuang.pojo.B">
        <property name="height"  value="456"></property>
    </bean>

    <bean id="b3"  class="com.kuang.pojo.B">
        <property name="height"  value="789"></property>
    </bean>


   //创建两个A类的对象a1和a2,a1对象有b属性,a2对象也有b属性

   //给a1这个对象的b属性赋值b1
    <bean id="a1"  class="com.kuang.pojo.A">
        <property name="b"  ref="b1"></property>
    </bean>

   //给a2这个对象的b属性赋值b2
    <bean id="a2"  class="com.kuang.pojo.A">
        <property name="b"  ref="b2"></property>
    </bean>

step4:测试类

public class MyTest
{
    public static void main(String[] args)
    {
      //创建出beans.xml文件里面的所有bean,这些bean放到spring这个容器里面进行管理
        ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");

        //拿到a1和a2两个bean
        A a1= (A) context.getBean("a1");
        A a2= (A) context.getBean("a2");

        System.out.println(a1.b.height);//123

        System.out.println(a2.b.height);//456
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值