spring_2_注入详解

1. 注入(Injection)

1.1 什么是注入?

注入:通过 Spring ⼯⼚及配置⽂件,为所创建对象的成员变量赋值。

1.2 为什么要注入?

  • 通过编码的⽅式,为成员变量进⾏赋值,存在耦合。
  • 注入的好处:解耦合。
public void test4() {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
    Person person = (Person) ctx.getBean("person");
    // 通过代码为变量赋值, 存在耦合, 如果我们以后想修改变量的值, 需要修改代码, 重新编译
    person.setId(1);
    person.setName("zhenyu");
    System.out.println(person);
}

1.3 如何进行注入[开发步骤]

  • 类的成员变量提供 set get ⽅法
  • 配置 spring 的配置⽂件
<bean id="person" name="p" class="com.yusael.basic.Person">
    <property name="id">
        <value>10</value>
    </property>
    <property name="name">
        <value>yusael</value>
    </property>
</bean>

1.4 Spring注入的原理分析(简易版)

Spring 底层通过 调用对象属性对应的 set 方法 ,完成成员变量的赋值,这种⽅式也称为 Set注入 。 img1

2. set注入详解

Set注入的变量类型:

  • JDK内置类型 8种基本类型 + String、数组类型、set集合、list集合、Map计划和、Properties集合。
  • 用户自定义类型

针对于不同类型的成员变量,在<property标签中,需要嵌套其他标签:

<property>
  xxxxx
</property>

img2

2.1 JDK内置类型

2.1.1 String+8种基本类型

<property name="id">
  <value>10</value>
</property>
<property name="name">
  <value>yusael</value>
</property>

2.1.2 数组

<property name="emails">
    <list>
        <value>abc@qq.com</value>
        <value>123@qq.com</value>
        <value>hello@qq.com</value>
    </list>
</property>

2.1.3 Set集合

<property name="tels">
  <set>
    <value>138xxxxxxxxxx</value>
    <value>139xxxxxxxxxx</value>
    <value>138xxxxxxxxxx</value><!--set会自动去重-->
  </set>
</property>
原文地址:https://www.cnblogs.com/instinct-em/p/13254231.html