Spring的DI依赖注入

Spring的DI依赖注入

什么是依赖注入

DI(Dependency Injection)

当程序运行的时候,让spring提供层与层之间的依赖对象。在创建容器时,为我们维护好它们之间的关系。我们在使用中,只需要提供构造方法或者set方法即可。简单说就是缺少什么,就传入什么。

构造方法注入

  • bean对象
/**
* Bean对象
*/
public class ConstructorDIDaoImpl implements ICustomerDao {

    private int id;
    private String name;
    private int age;
    private Date birthday;

    /**
    * 构造方法注入
    */
    public ConstructorDIDaoImpl(int id, String name, int age, Date birthday) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }
}
  • constructor-arg标签:指定调用构造方法实例化对象,初始化对象

  • 属性

    • index:指定参数,在构造方法参数列表中的索引
    • name:指定参数,在构造方法参数列表中的名称(与index使用一个即可)
    • type:指定参数类型(一般不用)
    • value:给参数赋值,针对八大数据类型的参数
    • ref:引用给参数赋值,针对其它bean类型
  • 配置文件

<!--配置构造方法注入的对象,说明:
constructor-arg标签:指定调用构造方法实例化对象,初始化对象
    属性:
        index:指定参数,在构造方法参数列表中的索引
        name:指定参数,在构造方法参数列表中的名称(与index使用一个即可)
        type:指定参数类型(一般不用,有时候配置了spring也有时候会认错,比如Integer不能自动封箱拆箱)
        value:给参数赋值,针对简单类型的参数(八种基本类型+字符串)
        ref:给参数赋值,针对其它bean类型
-->
<bean id="constructoryDao" class="com.dao.impl.ConstructorDlDaoImpl">
    <constructor-arg index="0" type="int" value="1"></constructor-arg>
    <constructor-arg name="1" value="小明"></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<bean id="now" class="java.util.Date"></bean>

Set方法注入

让spring使用类中的set方法,给成员变量赋值。

  • bean对象
public class ConstructorDIDaoImpl implements ICustomerDao {

    private int id;
    private String name;
    private int age;
    private Date birthday;

    get/set()......

}
  • property标签:指定调用set方法给成员变量赋值
  • 属性

    • name:赋值的成员变量的名称
    • value:给java简单类型的变量赋值
    • ref:给其它bean类型赋值
  • 配置文件

<!-- set方法注入,说明:在实际项目中,set注入的方式使用更多
    property标签:指定调用set方法给成员变量赋值
        属性:
            name:赋值的成员变量的名称
            value:给java简单类型的变量赋值
            ref:给其它bean类型赋值
 -->
<bean id="setDao" class="cn.dao.impl.SetDependencyDaoImpl">
    <property name="id" value="1"></property>
    <property name="name" value="Hello"></property>
    <property name="age" value="18"></property>
    <property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>

猜你喜欢

转载自blog.csdn.net/Kato_op/article/details/80220740