在Spring中有三种拆卸的形式:
- 在xml中显式的配置
- 在java中显式的配置
- 隐式的主动拆卸bean
在xml中显式的配置
援用 Spring-IOC创建对象的形式
在xml文件中配置对象属性
在java中显式的配置
援用 Spring-IOC实践推导
在理论调用dao层的时候,能够显示的配置选用哪个dao接口
隐式的主动拆卸bean
- 主动拆卸是Spring满足bean依赖的一种形式
- Spring会在上下文中主动寻找,并主动给bean拆卸属性
byName主动拆卸
<bean id="cat" class="com.sunfl.pojo.Cat"/>
<bean id="dog" class="com.sunfl.pojo.Dog"/>
<!--
byName:会主动在容器上下文查找,和本人对象set办法前面的值对应的beanid!
-->
<bean id="people" class="com.sunfl.pojo.People" autowire="byName">
<property name="name" value="向日葵"/>
</bean>
byType主动拆卸
<bean id="cat" class="com.sunfl.pojo.Cat"/>
<bean id="dog111" class="com.sunfl.pojo.Dog"/>
<!--
byType:会主动在容器上下文查找,和本人对象属性类型雷同的bean!
-->
<bean id="people" class="com.sunfl.pojo.People" autowire="byType">
<property name="name" value="向日葵"/>
</bean>
小结:
- byName的时候,须要保障所有的bean的id惟一,并且这个bean须要和主动注入的属性set办法的值统一
- byType的时候,须要保障所有的bean的class惟一,并且这个bean须要和主动注入的属性类型统一
应用注解实现主动拆卸
jdk1.5反对注解,Spring2.5反对注解
- 导入束缚:context束缚
-
配置注解的反对:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <bean id="cat" class="com.sunfl.pojo.Cat"/> <bean id="dog" class="com.sunfl.pojo.Dog"/> <bean id="people" class="com.sunfl.pojo.People"/> <!--开启注解的反对--> <context:annotation-config/> </beans>
@Autowired
间接在属性上应用即可,也能够在set办法上应用
应用Autowired咱们能够不必编写Set办法了,前提是你这个主动拆卸的属性在IOC(Spring)容器中存在,且合乎名字byName
如果@Autowired主动拆卸的环境比较复杂,主动拆卸无奈通过一个注解【@Autowired】实现的时候,咱们能够应用@Qualifier(value=”xxx”)去配置@Autowired的应用,指定一个惟一的bean对象注入
public class People {
@Autowired
@Qualifier(value = "cat111")
private Cat cat;
@Autowired
@Qualifier(value = "dog222")
private Dog dog;
private String name;
}
@Resource注解
public class People {
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String name;
}
小结:
@Resource和@Autowired的区别:
- 都是用来主动拆卸的,都能够放在属性字段上
- @Autowired通过byType的形式实现【罕用】
- @Resource默认通过byName的形式实现,如果找不到名字,则通过byType实现
发表回复