spring classpath
1, 编译时依赖 :
dest/*.jar
2, 运行依赖:
dom4j.jar , jakarta-commons.*.jar ,antalr.jar , cglib.jar , aopallians.jar
asm.jar
IOC 依赖注入
注入:通过spring容器将为bean设置所需要的属性。
1) 通过set方法
<bean id=”” class=””>
<property name=””>
<value></value> | <ref></ref> | list | set | map |props
</property>
</bean>
id : 该javabean在spring框架中的唯一标识 。
class : 该javabean的类型 。
value : 使用常量 。
ref : 引用其他Bean , 也可以使用内部bean
内部bean指声明在其他bean标签内部的bean,内部bean的声明
只能在外部标签中使用。
list : List用于注入List或数组类型的成员变量。
List 中的值可以是常量也可以是其他bean的定义
<property name="addresses">
<list>
<value>xxx</value>
<ref bean=""></ref>
</list>
</property>
set :set的用法和List一致,唯一的区别就是注入不同类型的成员变量。
<property name="addresses">
<set>
<value>xxx</value>
<ref bean=""></ref>
</set>
</property>
map :用于注入Map类型的成员变量,其值由Entry组成,Entry包含Key和value两种信息。
<property name="friends ">
<map>
<entry key="xxx">
<value>xxxxx</value>|<ref></ref>
</entry>
</map>
</property>
Map中的key和value可以是任何类型
<property name=”xxxx”>
<map>
<entry>
<key>
<value></value>|<ref bean></ref>
</key>
<value>xxx</value>|<ref></ref>
</entry>
<map>
</property>
props: 用于装配Properties类型的成员变量 :
<property name="xxx">
<props>
<prop key="key1">valueA</prop>
<prop key="key2">valueB</prop>
<props>
</property>
由于 Properties对象中的Key和Value只能是字符串,所以prop的值
部分就不需要通过<value></value>标签特殊指定。
注入NULL : 如果一个属性的值为空,我们可以通过<null/>标签来注入。
<property name="xxx">
<null/>
</property>
2) 通过构造函数
<bean id="" class="">
<constructor-arg>
<value></value>|<ref></ref>|......
</constructor-arg>
</bean>
constructor-arg 标签用于指定构造函数所需要的参数。
参数的值可以是 常量<value></value>,或者其他的bean <ref></ref>
2.1) 解决构造函数参数的不确定性
<constructor-arg index=""></constructor-arg>
<constructor-arg type=""></constructor-arg>
3)自动注入 :
通过<value>或<ref>标签可以显示的注入值, 在Spring中还存在自动装配的方法。
<bean id="a" class="a.Test" autowire="type"/>
autowire: 表示 a 的各个成员变量的值由Spring自动注入,注入方式由参数Type指定。
Type 的可能取值 :
byName : 在配置文件中查找与属性同名的bean,即( 配置文件中bean的Id与成员
变量的值一致) 如果没有找到,则该值为空。
byType : 在配置文件中查找与这个属性类型相同的bean , 如果没有找到,则该值
为空,如果找到超过一个的bean 则抛出
org.springframework.beans.factory.UnsatisfiedDependencyException ;
constructor :试图在容器中查找与自己构造函数参数类型一致的一个或多个bean , 如果被注入的Bean有超过一个的构造函数,或者无法找到所有需要的参数容器抛出异常:
org.springframework.beans.factory.UnstatisfiedDependencyException;
autodetect :首先尝试 使用 construcotr , 然后使用byType 。
自动注入和手动注入可以混合使用 :
在指定autowire的同时也可以指定<property>. 这样可以解决byType产生的不确定性问题。
缺省自动装配 :
<beans default="byType"> 这样所有的bean都会采用同样的自动装配过程 ,
除非在<bean>标签中显示指定了自己的自动装配方法。
自动装配会带来很多问题,如一个bean的属性名称经过修改,那么在配置文件中对应的所有byName的Bean就会无法注入。
自动装配隐藏了很多实现细节,而我们希望在配置文件中注入的过程能够足够清晰,所以使用自动装配要谨慎。