Spring框架(四):spring的依赖注入

一、spring依赖注入的简介

1、依赖注入的定义

DI(Dependency Inject,依赖注入),容器通过调用set方法或者构造器来建立对象之间的依赖关系。

2、依赖注入的作用

spring核心容器通过依赖注入建立对象之间的依赖关系,降低程序间的耦合。

二、spring依赖注入的方式

1、使用构造方法注入

1.1、构造注入使用constructor-arg标签

<!--构造方法注入-->
<bean id="constructor" class="com.wedu.spring02.entity.UserInfo">
    <constructor-arg name="id" value="1"/>
    <constructor-arg name="username" value="test"/>
    <constructor-arg name="password" value="123456"/>
    <constructor-arg name="age" value="25"/>
    <constructor-arg name="regtime" ref="now"/>
    <constructor-arg name="siteaddress" value="https://mp.csdn.net/postedit/103544678"/>
</bean>

 1.2、constructor-arg标签的属性

  • type:用于指定要注入的数据的数据类型。
  • index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始。
  • name:用于指定给构造函数中指定名称的参数赋值。
  • value:用于提供基本类型和String类型的数据。
  • ref:用于指定其他的bean类型数据。

1.3、优缺点

  • 优点:在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功。
  • 缺点:改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供。

2、使用set方法注入

2.1、set方法注入使用标签property

<!--set方法注入-->
<bean id="property" class="com.wedu.spring02.entity.UserInfo">
    <property name="id" value="1"/>
    <property name="username" value="test"/>
    <property name="password" value="123456"/>
    <property name="age" value="25"/>
    <property name="regtime" ref="now"/>
    <property name="siteaddress" value="https://mp.csdn.net/postedit/103544678"/>
</bean>

2.2、property标签的属性

  • name:用于指定注入时所调用的set方法名称。
  • value:用于提供基本类型和String类型的数据。
  • ref:用于指定其他的bean类型数据。

2.3、优缺点

  • 优点:创建对象时没有明确的限制,可以直接使用默认构造函数
  • 缺点:如果有某个成员必须有值,则获取对象是有可能set方法没有执行。

三、复杂类型的依赖注入

<!--复杂类型注入-->
<bean id="userInfo" class="com.wedu.spring02.entity.UserInfo">
    <!--数组类型注入-->
    <property name="arr">
        <array>
            <value>hello</value>
            <value>world</value>
        </array>
    </property>
    <!--list集合类型注入-->
    <property name="list">
        <list>
            <value>hello</value>
            <value>world</value>
        </list>
    </property>
    <!--set集合类型注入-->
    <property name="set">
        <set>
            <value>hello</value>
            <value>world</value>
        </set>
    </property>
    <!--map集合类型注入-->
    <property name="map">
        <map>
            <entry key="zhangsan" value="18"/>
            <entry key="lisi">
                <value>25</value>
            </entry>
        </map>
    </property>
    <!--properties类型注入-->
    <property name="properties">
        <props>
            <prop key="username">赵六</prop>
            <prop key="password">123456</prop>
        </props>
    </property>
</bean>
发布了134 篇原创文章 · 获赞 10 · 访问量 7358

猜你喜欢

转载自blog.csdn.net/yu1755128147/article/details/103544678