Spring 支持两种依赖注入方式,分别为构造函数注入和属性注入,此外还支持工厂方法注入方式。
构造函数注入
构造函数注入由容器调用带参的构造函数来完成,与通过调用指定参数的静态工厂方法来构造 bean 相似。包含构造函数的类是一个没有依赖于容器指定的接口,基类或注释的 POJO,如下所示:
构造函数参数解析
使用参数的类型进行构造函数参数解析匹配。如果 bean 定义的构造函数参数不存在歧义,那么构造函数参数在 <beans/>
中定义的参数顺序和 bean 被实例化时提供给适当的构造函数的参数顺序一致。
|
|
按类型匹配入参
在 <constructor-arg>
的元素中有一个 type 属性,它为 Spring 提供了判断配置项和构造函数入参对应关系的信息。Spring 的配置文件采用和元素标签顺序无关的策略,在一定程度上保证配置信息的正确性,<constructor-arg>
位置的改变并不会对最终的配置产生影响。
|
|
按索引匹配入参
如果构造函数两个入参的类型相同,仅通过 type 无法确定对应关系,需要通过入参索引的方式进行确定,参数和构造函数参数需要顺序对应。
按参数名匹配入参
使用 @ConstructorProperties 注解指定入参名,在 xml 文件中通过参数名的方式匹配入参。
|
|
属性注入
属性注入即通过 setXxx() 方法注入 Bean 的属性值或依赖对象,由于属性注入方式具有可选择性和灵活性高的优点,因此属性注入是实际应用中最常见的注入方式。属性注入要求 Bean 提供一个默认的构造函数,并为需要注入的属性提供对应的 Setter 方法。Spring 先调用 Bean 的默认构造函数实例化 Bean 对象,然后通过反射的方式调用 Setter 方法注入属性值。
|
|
注入参数详解
字面值
字面值指可用字符串表示的值,且这些值可通过 value 属性进行注入。Spring 容器在内部为字面值提供了编辑器,它可以将以字符串表示的字面值转换为内部变量的相应类型。
使用 p-namespace 简化上述的 xml 配置:
引用其他 bean
使用 ref 指定引用的 bean:
|
|
内部 Bean
内部 Bean 和 Java 代码中匿名内部类相似,没有名字,也不能被其他 Bean 引用,只能在声明出为外部 Bean 提供实例注入。内部 Bean 即使提供了 id、name、scope 属性,也会被忽略,scope 默认为 prototype类型。
集合类型属性
在 ,
集合合并
允许子 <bean>
继承父 <bean>
的同名属性集合元素,并将子 <bean>
中配置的集合属性值和父 <bean>
中配置的同名属性值合并起来作为最终 Bean 的属性值。
强类型集合
JDK5.0 提供了强类型集合的新功能,允许为集合元素指定类型。
|
|
null 值和空 string 值
参数值为空 String:
参数值为 null:
简化配置方式
Spring 为字面值、引用 Bean 和集合都提供了简化的配置方式。
使用 p-namespace
|
|
使用 c-namespace
|
|
级联属性
|
|
foo bean 有一个 fred 属性,在 fred 下有一个 bob 属性, 在 bob 下有一个 sammy 属性。