spring IOC和DI

spring IOC and DI
1、IOC和DI的区别:
IOC:对象的管理权由spring容器掌握(管理权限包括:对象的创建时间点、创建方式以及对象属性的管理);
DI:spring操作对象属性的时使用的方式就是DI技术

2、DI方式:spring操作对象属性的时间点一般都是在对象创建的时候,操作的方式是可配置的,主要有4种方式:no(default)、byName、byType、constructor。
no方式:这是spring的默认方式,这种方式spring不会对对象的属性做任何的操作,除非配置了<property>属性,否则spring不会自动的在当前context去找需要的值。
byName方式:spring会在当前的context找到和对象属性名称相同的值进行注入,如果找到的值的类型和属性的值类型不一致就会报:"Cannot convert value of type"错误。
byType方式:spring会在当前的context找到和对象属性类型相同的值进行注入,如果找到值不止一个就会报"No unique bean of type"错误。
constructor方式:这种方式比较特殊,这是一个显示的依赖关系,对象必须有有参构造方法,spring会根据参数的名称去context找对应的值进行注入,改方式不能被子类继承。

3、IOC用法:
3.1、创建子类对象,给其指定父类对象,如果不指定那么父类会重新实例化,不会再当前容器中查找。
<bean name="student" class="com.xxw.pojo.Student" parent="persion">
<property name="name" value="this a student"/>
</bean>
<bean name="persion" class="com.xxw.pojo.Persion" autowire="byName" >
<property name="persionName" value="this is two persion"/>
</bean>
其他两种:可以通过静态工厂方法或者实例工厂的方法

4、spring元数据配置中的p标签和c标签
使用p标签需要加入xml:xmlns:p="http://www.springframework.org/schema/p"
<bean name="animal" class="com.xxw.pojo.Cat" p:name="this is cat" />
等价于:
<bean name="animal" class="com.xxw.pojo.Cat">
<property name="name" value="this is cat"/>
</bean>
使用c标签需要加入xml: xmlns:c="http://www.springframework.org/schema/c"
这个标签的使用类似于:<constructor-arg></constructor-arg>标签。

posted on 2014-04-06 00:06  把-大象装进-冰箱  阅读(205)  评论(0编辑  收藏  举报