Spring的核心功能之一便是IOC(控制反转),其作用便是降低类与类之间的依赖,降级程序间的耦合,便于之后的代码维护,但想要完全消除类与类之间的依赖关系是不可能的。

那么这里将类与类之间的依赖交给spring来管理,在当前类需要用到其他类的时候,由spring来提供,我们只需在配置文件进行配置即可。

那么,所谓的依赖注入便是依赖关系之间的维护

能够注入的数据有3类

1.基本类型和String

2.其他bean类型(在配置文件或者注解配置过的bean)

3.复杂类型/集合类型

注入的方式也有3种

1.使用构造函数提供

2.使用set方式提供

3.使用注解提供

 

一.构造函数提供

public class AccountDaoImpl implements AccountDao {
    Integer aaa;
    int bbb;
    String ccc;
    Date ddd;

    public AccountDaoImpl(Integer aaa, int bbb, String ccc, Date ddd) {
        this.aaa = aaa;
        this.bbb = bbb;
        this.ccc = ccc;
        this.ddd = ddd;
    }

    @Override
    public String toString() {
        return "AccountDaoImpl{" +
                "aaa=" + aaa +
                ", bbb=" + bbb +
                ", ccc='" + ccc + '\'' +
                ", ddd=" + ddd +
                '}';
    }
    
}

 

配置文件

<bean id="accountDao" class="com.itylm.dao.Impl.AccountDaoImpl">
    <constructor-arg name="aaa" value="12"></constructor-arg>
    <constructor-arg name="bbb" value="15"></constructor-arg>
    <constructor-arg name="ccc" value="优乐美"></constructor-arg>
    <constructor-arg name="ddd" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>

使用标签:constructor-arg(在bean标签内部)

标签属性

name:用于指定构造函数指定的名称的参数赋值(最常用)

type:用于指定要注入的数据类型

index:用于指定要注入的数据给构造函数中指定索引位置的参数赋值,索引从0开始

value:用于提供String和基本数据类型的数据

ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象

使用该方法的特点是数据必须注入,否则无法创建对象

 

二.set方法提供


<bean id="accountDao" class="com.itylm.dao.Impl.AccountDaoImpl">
    <property name="aaa" value="12"></property>
    <property name="bbb" value="46"></property>
    <property name="ccc" value="4567"></property>
    <property name="ddd" ref="now"></property>
</bean>


使用标签:property(在bean标签内部)

标签属性

name:用于指定构造函数指定的名称的参数赋值、

value:用于提供String和基本数据类型的数据

ref:用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象

使用该方法的特点是没有明确的限制,可以使用默认的构造函数方法,如果有必要的值注入,该方法无法保证

最后一种注解提供在后边进行总结