bean的自动装配
在Spring中有三种装配的方式
- 在xml中显示配置
- 在java中显示配置
- 隐式自动装配bean
1.测试环境搭建
一人一猫一狗
2.byName自动装配
在容器上下文中找和自己对象set方法后面的值对应的bean id
bean的id必须是唯一的
<bean id="cat" class="cn.pinked.pojo.Cat"/>
<bean id="dog" class="cn.pinked.pojo.Dog"/>
<bean id="people" class="cn.pinked.pojo.people" autowire="byName">
<property name="name" value="大头儿子"/>
</bean>
3.byType自动装配
在容器上下文中找和自己对象属性类型相同的bean
bean的class必须是唯一的
bean中可以没有id
<bean class="cn.pinked.pojo.Cat"/>
<bean class="cn.pinked.pojo.Dog"/>
<bean id="people" class="cn.pinked.pojo.people" autowire="byType">
<property name="name" value="大头儿子"/>
</bean>
4.@Autowired注解自动装配
-
导入约束-------------------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" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <context:annotation-config/> <bean id="cat" class="cn.pinked.pojo.Cat"/> <bean id="dog" class="cn.pinked.pojo.Dog"/> <bean id="people" class="cn.pinked.pojo.people"/> </beans>
-
在属性上使用注解@Autowired
使用@Autowired后可以不用再编写set方法了
@Autowired private Cat cat; @Autowired private Dog dog;
如果required的值为false,那么该对象可以为NULL,否则不能为空
@Autowired(required = false)
-
当自动装配无法通过一个注解@Autowired完成时,可以通过@Qualifier配置使用,指定唯一的一个bean对象注入
@Autowired @Qualifier(value = "cattttt") private Cat cat; @Autowired @Qualifier(value = "doggggg") private Dog dog;
5.@Resource注解自动装配
-
java提供的注解
@Resource private Cat cat; @Resource private Dog dog;
@Autowired与@Resource:
相同点:
- 都是用来自动装配的,都可以放在属性的字段上
不同点:
- @Autowired默认通过byType方式实现
- @Resource默认通过byName方式实现,如果找不到结果再通过byType实现