Spring使用Set注入和拓展注入

Spring中有三种方式注入,第一种是之前文章所写的构造器注入,第二种是使用Set注入,第三种是拓展注入(利用标签)

使用Set注入:

使用的pojo为:

并生成get和set方法

XML配置:

<bean id="address" class="com.mi.pojo.Address">
    <property name="address" value="广州"></property>
</bean>
<bean id="student" class="com.mi.pojo.Student">
    <!--第一种,普通值注入,value-->
    <property name="name" value="芈"></property>
    <!--Bean注入,ref-->
    <property name="address" ref="address"></property>
    <!--数组注入,ref-->
    <property name="books" >
        <array>
            <value>西游记</value>
            <value>三国演义</value>
        </array>
    </property>
    <!--List-->
    <property name="hobby">
        <list>
            <value>唱</value>
            <value>跳</value>
        </list>
    </property>
    <!--Map-->
    <property name="card">
        <map>
            <entry key="身份证" value="111111111"></entry>
            <entry key="银行卡" value="1111564"></entry>
        </map>
    </property>
    <!--Set-->
    <property name="games">
        <set>
            <value>DNF</value>
            <value>LOL</value>
        </set>
    </property>
    <!--null-->
    <property name="wife">
        <null></null>
    </property>
    <!--Properties-->
    <property name="info">
        <props>
            <prop key="username">root</prop>
            <prop key="url">155441235</prop>
            <prop key="password">root</prop>
        </props>
    </property>

</bean>

拓展注入:

使用标签注入必须导入对应的依赖

<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"
       xmlns:c="http://www.springframework.org/schema/c"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

使用的pojo:

提供get和set方法

XML中使用P标签配置:

<bean id="user" class="com.mi.pojo.User" p:name="芈" p:age="18"></bean>

测试结果:

使用p标签直接注入属性的值,而调用无参构造器是用来创建对象

XML中使用C标签配置:

<bean id="user2" class="com.mi.pojo.User" c:name="芈2" c:age="18"></bean>

测试结果:

使用c标签是利用有参构造器注入属性的值

猜你喜欢

转载自blog.csdn.net/qq_42500503/article/details/108937543
今日推荐