IOC. DI(依赖注入 为类类型赋值)

为类类型的属性赋值

 第一种方式:引用外部bean

package com.atguigu.spring.pojo;

public class Clazz {
   private Integer cid;
   private String cname;
  ...
}
package com.atguigu.spring.pojo;

public class Student {
   private Integer sid;
   private String sname;
   private String gender;

   private Clazz clazz;
  ...
}

  ref 属性:通过 bean 的 id 引用另一个 bean

<!-- ref(引用):引用的是当前IOC容器中的某一个bean的id来为当前属性赋值   -->
   <bean id="studentFive" class="com.atguigu.spring.pojo.Student">
       <property name="sid" value="1002"></property>
       <property name="sname" value="赵六"></property>
       <property name="gender" value="男"></property>
       <property name="clazz" ref="clazzOne"></property>
   </bean>
   <bean id="clazzOne" class="com.atguigu.spring.pojo.Clazz">
       <property name="cid" value="111"></property>
       <property name="cname" value="最强spring"></property>
   </bean>
 @Test
   public void testDI(){
       ApplicationContext ioc=new ClassPathXmlApplicationContext("ApplicationContext.xml");
       Student bean = ioc.getBean(Student.class);
       System.out.println(bean);
  }
//Student{sid=1002, sname='赵六', gender='男', clazz=Clazz{cid=111, cname='最强spring'}}

 第二种方式:级联方式(用的不多)

        要保证提前为clazz属性赋值或者实例化

 

  第三种方式:内部bean方式

      在bean里面配置的bean就是内部bean,内部bean只能在当前bean内部使用,在其他地方不能使用。

 <bean id="studentFive" class="com.atguigu.spring.pojo.Student">
       <property name="sid" value="1002"></property>
       <property name="sname" value="赵六"></property>
       <property name="gender" value="男"></property>
       <property name="clazz">
<!-- 内部bean:只能在当前bean的内部使用,不能直接通过IOC容器获取-->
           <bean id="clazzInner" class="com.atguigu.spring.pojo.Clazz">
               <property name="cid" value="2222"></property>
               <property name="cname" value="远大前程"></property>
           </bean>
       </property>
   </bean>
 
posted @ 2022-11-12 21:25  zjw_rp  阅读(145)  评论(0)    收藏  举报