spring:DI依赖注入

1.构造器注入

    <bean id="student" class="com.ultraBlast.pojo.Student">
        <!--第一种注入方式:普通值注入,直接使用value-->
        <property name="name" value="UB"/>
    </bean>

2.Set注入

  • 依赖注入:Set注入!
    • 依赖:bean对象的创建依赖于容器
    • 注入:bean对象中的所有属性,由容器来注入!

【环境搭建】

  • 复杂类型
  • 真实测试对象
    <bean id="address" class="com.ultraBlast.pojo.Address">
        <property name="address" value="无锡"/>
    </bean>
    <bean id="student" class="com.ultraBlast.pojo.Student">
        <!--第一种:普通值注入,value-->
        <property name="name" value="UB"/>
        <!--第二种:Bean注入,ref方式传值-->
        <property name="address" ref="address"/>
        <!--数组注入,ref-->
        <property name="books">
            <array>
                <value>红楼梦</value>
                <value>三国演义</value>
                <value>水浒传</value>
                <value>西游记</value>
            </array>
        </property>
        <!--List-->
        <property name="hobbies">
            <list>
                <value>听歌</value>
                <value>下棋</value>
                <value>会话</value>
            </list>
        </property>
        <!--Map-->
        <property name="cards">
            <map>
                <entry key="身份证" value="12312312312"/>
                <entry key="银行卡" value="12312312312"/>
            </map>
        </property>
        <!--Set-->
        <property name="games">
            <set>
                <value>LOL</value>
                <value>COC</value>
                <value>BOB</value>
            </set>
        </property>
        <!--空值null-->
        <property name="wife">
            <null></null>
        </property>
        <!--properties-->
        <property name="info">
            <props>
                <prop key="学号">123131</prop>
                <prop key="性别">男</prop>
                <prop key="姓名">张三</prop>
            </props>
        </property>
    </bean>

3.拓展方式注入

我们可以使用p命名空间和c命名空间进行注入
官方解释:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean name="classic" class="com.example.ExampleBean">
        <property name="email" value="someone@somewhere.com"/>
    </bean>

    <bean name="p-namespace" class="com.example.ExampleBean"
        p:email="someone@somewhere.com"/>
</beans>

注意点:p命名和c命名空间不能直接使用,需要导入xml约束语句

xmlns:p="http://www.springframework.org/schema/p"
xmlns:c="http://www.springframework.org/schema/c"
posted @ 2021-03-31 21:07  UltraBlast  阅读(43)  评论(0)    收藏  举报