IOC. DI(依赖注入setter和构造器注入)

  依赖注入之setter注入(常用)

       依赖注入:就是为当前实体(类) 中的属性进行赋值过程就叫做依赖注入

 setter注入:设置property就会在底层为set方法为当前属性赋值,调用哪个给哪个赋值

package com.atguigu.spring.pojo;

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

  在配置时给属性指定值

<!--
   ref:引用
   value:赋普通值
-->
   <bean id="studentOne" class="com.atguigu.spring.pojo.Student" >
<!--
   property:通过成员变量的set方法进行赋值
   name:设置需要赋值的 属性名(和set方法有关)
   value:设置为属性所赋的值
   如果在IOC容器这个配置文件中:只要看到bean标签的property用的就是当前setter注入
   通过setter方法来为赋值
-->
       <property name="sid" value="1001"></property>
       <property name="sname" value="张三"></property>
       <property name="gender" value="男"></property>
   </bean>

@Test
   public void testDI(){
   ApplicationContext ioc=new ClassPathXmlApplicationContext("ApplicationContext.xml");
       Student bean = ioc.getBean(Student.class);
       System.out.println(bean);
  }

 

   依赖注入之构造器注入

 <bean id="studentThree" class="com.atguigu.spring.pojo.Student">
<!--
   name:设置当前参数名,而不是属性名,因为对应的是有参构造,
       如果只有一个有参构造,直接为参数按顺序赋值,用value
     例如:  如果有两个有参构造,前几个属性相同,后一个不相同,
           想匹配给第一个构造,给最后一个属性赋值,要指明最后一个不相同的参数名:name
-->
       <constructor-arg value="1002"></constructor-arg>
       <constructor-arg value="李四"></constructor-arg>
       <constructor-arg value="女"></constructor-arg>
   </bean>

  @Test
   public void testDI(){
       ApplicationContext ioc=new ClassPathXmlApplicationContext("ApplicationContext.xml");
       Student bean = ioc.getBean(Student.class);
       System.out.println(bean);
  }
 

 

posted @ 2022-11-11 21:14  zjw_rp  阅读(19)  评论(0)    收藏  举报