spring依赖注入

Dependency injection (DI),依赖注入主要有两种方式

  • 构造器注入,是容器通过类的构造器进行注入的,构造器中有一系列的参数,每一个参数都是一个依赖
  • setter注入,容器通过类的setter方法进行注入

现在有一个pojo类,具体定义如下:

package student;

public class StudentBean {
	//student id
    private int id;

    // student name
    private String name;

    public StudentBean(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

通过构造器进行注入

首先要求这个类具有有参的构造函数,利用bean标签下的constructor-arg进行构造器注入。

利用参数的类型

根据构造器里的参数的类型进行注入,在constructor-arg标签内利用type指定参数的类型,用value进行赋值,如果是自定义类型,用ref进行赋值。推荐在各参数类别都不一致时使用,如果有多个参数有同一类型,则要保证注入的顺序。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean name="student" class="Student">
        <constructor-arg type="int" value="7"/>
        <constructor-arg type="java.lang.String" value="studentname"/>

    </bean>
</beans>

利用参数的下标
可以利用参数的下标,即构造器中各参数的顺序来进行注入,使用constructor-arg标签的index属性。index的值从0开始,index的值与构造其中参数出现的顺序有关。

        <constructor-arg index="0" value="7"/>
        <constructor-arg index="1" value="studentname"/>

利用参数的name
为了消除歧义,还可以利用参数名进行注入,使用constructor-arg的name属性。

	    <constructor-arg name="id" value="7"/>
        <constructor-arg name="name" value="studentname"/>

通过setter进行注入

要求要注入的参数具有它的setter方法,并且利用property标签进行注入。

        <property name="id" value="7"/>
        <property name="name" value="studentname"/>

collection进阶

对于list、map、set以及properties等类型的元素,操作有些不同,我们现在再创建一个类

public class Teacher {

    private Set set;
    private List list;
    private Map map;
    private Properties properties;
	//省略setter和tostring
}

下面通过实例,来说明如何给这些类型的元素注入值

<bean name="teacher" class="Teacher">
        <property name="properties">
            <props>
                <prop key="id">7</prop>
                <prop key="name">teachername</prop>
            </props>
        </property>
        <property name="set">
            <set>
                <value>student1</value>
                <value>student2</value>
                <ref bean="student"></ref>
            </set>
        </property>
        <property name="list">
            <list>
                <value>7</value>
                <value>teacher</value>
                <ref bean="student"></ref>
            </list>
        </property>
        <property name="map">
            <map>
                <entry key="id" value="7"/>
                <entry key="name" value="teachername"/>
                <entry key="student" value-ref="student"/>
            </map>
        </property>
    </bean>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值