从前面到现在,全部是自己手动的装配属性!
Bean的自动装配
- 自动装配是Spring满足Bean依赖的一种方式!
- Spring会在上下文中自动寻找,并自动给bean装配属性!
在Spring中有三种装配的方式:
- 在xml中显示的配置
- 隐式的自动装配 bean
- 在Java中显示的配置
在xml中显示的配置
前面所讲的都是在xml中显示配置
隐式的自动装配 bean
- byType:会自动在容器上下文中,查找和自己属性类型相同的唯一bean
- byName:会自动在容器上下文中,查找和自己对象set方法后面的值相同的beanid
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="dog" class="com.shang.Dog"></bean>
<bean id="cat" class="com.shang.Cat"></bean>
<bean id="people" class="com.shang.People" autowire="byName"></bean>
</beans>
注解实现自动装配(在Java中显示的配置)
@Autowired、@Qualifier、@Primary、@Resource
- 开启注解功能
<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
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="dog" class="com.shang.Dog"></bean>
<bean id="cat1" class="com.shang.Cat"></bean>
<bean id="cat2" class="com.shang.Cat"></bean>
<bean id="people" class="com.shang.People"></bean>
</beans>
- 自动装配可以不要set方法
- @Autowired 是先按类型查找,再按照名字查找。默认必须找到,@Autowired(required = false)允许找不到也不报错
- @Autowired 与 @Qualifier(“xxx”) 搭配使用,是按照名字查找
- @Resource 是先按照名字查找,再按照类型查找
public class People {
@Autowired
private Dog dog;
@Autowired
@Qualifier("cat1")
private Cat cat;