Spring学习笔记-自动装配Bean
-
自动装配是Spring满足bean依赖的一种方式
-
Spring会在上下文中自动寻找,并自动给bean装配属性
在Spring中有三种装配的方式
- 在xml中显式的配置
- 在Java中显式配置
- 隐式的自动装配bean
ByName
通过参数名进行自动装配,当容器发现Autowire属性被更改为byName时,会自动在容器上下文寻找,和自己对象set方法后面的值相对应的beanId
弊端:如果beanId与set方法后的名字不匹配,则无法装配
<bean id="human" class="com.alb.pojo.Human" autowire="byName">
<property name="name" value="Alb"/>
</bean>
ByType
通过参数类型进行自动装配,当容器发现Autowire属性被改为byType时,会自动在容器上下文寻找和自己对象类型属性相同的bean
弊端:如果存在多个同类型的bean,则会抛出异常
<bean id="human" class="com.alb.pojo.Human" autowire="byType">
<property name="name" value="Alb"/>
</bean>
使用注解实现自动装配
使用注解前提:
- 导入约束:context约束
- 配置注解的支持:<context:annotation-config/ >
<?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"
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">
<context:annotation-config/>
</beans>
@Autowired
直接在属性上使用即可,也可以在set方法上使用
使用@Autowired后可不用编写setter方法,但是前提是这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byType
<?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"
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">
<context:annotation-config/>
<bean id="cat" class="com.alb.pojo.Cat"/>
<bean id="dog" class="com.alb.pojo.Dog"/>
<bean id="human" class="com.alb.pojo.Human" autowire="byType"/>
</beans>
测试类:
public class MyTest {
@Test
public void test(){
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Human human = context.getBean("human", Human.class);
human.getCat().bark();
human.getDog().bark();
}
}
拓展:
- 如果显式定义了AutoWired的require属性为false,说明这个对象可以为null,否则不能为空
- @Nullable:如果字段标记了这个注解,说明这个字段可以为空
- 如果@Autowired自动装配的环境比较复杂,如多个同类型不同id的bean,自动装配无法通过一个注解(@Autowired)完成的时候,我们可以使用@Qualifier(value = “xxx(beanId)”)去配合@Autowired的使用,指定一个唯一的bean对象注入
@Resource 和 @Autowired 的区别:
-
都是用来自动装配,都可以放在属性字段上
-
@Autowired 是通过byType的方式实现,而且必须要求改对象存在
-
@Resource 默认通过byName的方式实现,若找不到名字,则通过byType实现,若两个方式都找不到的情况下,会报错
-
执行顺序不同