Spring——依赖注入

概述

依赖注入就是给指定bean的属性赋值,通常有两种方法:
1、通过构造器赋值;
2、通过setter赋值

构造器注入

1、按参数顺序注入:
需要用到constructor-arg,并且在目标类中需要定义构造函数,其参数数量与对应的bean中的constructor-arg数量相同。其中的index属性值就是目标类中属性的定义顺序。
目标类:
Spring——依赖注入
applicationContext.xml配置:
Spring——依赖注入
测试类:
Spring——依赖注入
2、按参数类型注入:
通过constructor-arg的type属性来指定
目标类:
Spring——依赖注入
applicationContext.xml配置:
Spring——依赖注入

通过setter注入

此方式区别于构造器注入方式主要在于需要对目标类的属性进行set/get实现,再通过在applicationContext.xml中的property来进行赋值操作。
1、使用setter方法注入
目标类:
Spring——依赖注入
applicationContext.xml文件:
Spring——依赖注入
测试类:
Spring——依赖注入
2、引用其他bean
就是通过一个bean得到另一个bean的对象,可用property的ref属性来指定并调用。
目标类同上(被调用者)
另一个类(调用者):
Spring——依赖注入
applicationContext.xml配置文件:
Spring——依赖注入
测试类:
Spring——依赖注入