Bean的自动装配
- 自动装配是Spring满足bean依赖的一种方式
- Spring会在上下文中自动寻找,并且自动给bean装配属性
在spring中有是那种装配的方式
- 在xml中显示的配置
- 在java中显示配置
- 隐式的自动装配bean(重点)
创建新的子模块
7.1、测试
- 环境搭建
一个人有两个宠物!
项目结构如下:
public class Cat {
public void shout(){
System.out.println("miao~");
}
}
public class Dog {
public void shout(){
System.out.println("wang~");
}
}
public class People {
private Cat cat;
private Dog dog;
private String name;
}
省略set get tostring方法
<bean id="dog" class="com.cxq.pojo.Dog"></bean>
<bean id="cat" class="com.cxq.pojo.Cat"></bean>
<bean id="people" class="com.cxq.pojo.People">
<property name="name" value="老倩呀"/>
<property name="cat" ref="cat"/>
<property name="dog" ref="dog"/>
</bean>
@Test
public void test1(){
/*1:拿到容器空间,new一个CPX*/
ApplicationContext context=new ClassPathXmlApplicationContext("beans.xml");
/*2:getBean
* 3:为了不进行强制类型转换,所以写死, 加上People.class*/
People people=context.getBean("people", People.class);
people.getDog().shout();
people.getCat().shout();
}
运行结构如下:
7.2、ByName自动装配
<!--ByName会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid-->
<bean id="people" class="com.cxq.pojo.People" autowire="byName">
<property name="name" value="老倩呀"/>
</bean>
7.3、ByType自动装配
<bean id="dog" class="com.cxq.pojo.Dog"></bean>
<bean id="cat" class="com.cxq.pojo.Cat"></bean>
<!--ByName会自动在容器上下文中查找,和自己对象set方法后面的值对应的beanid
ByType会自动在容器上下文中查找,和自己对象属性类型相同的bean
-->
<bean id="people" class="com.cxq.pojo.People" autowire="byType">
<property name="name" value="老倩呀"/>
</bean>
小结:byname时候,需要保证所有bean的id唯一,并且这个bean 需要和自动注入的属性的set方法的值唯一;
bytype时候,需要保证所有bean的class唯一,并且这个bean 需要和自动注入的属性的类型一致;
7.4、使用注解实现自动装配
要使用注解须知:
- 导入约束: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
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/>
</beans>
在属性前加入:@Autowared【直接在属性前加入即可】
测试通过:
也可以在set方式上使用,而且使用Autowired我们可以不用编写set方法,前提是你这个自动装配的属性在IoC(Spring)容器中存在而且符合名字ByName。
科普:
@Nullable 字段如果标记了这个注解,说明这个字段可以为空null
测试代码:
public class People {
/*如果显式的定义了Autowired的required属性为false,说明这个属性可以为空,否则不可以为空*/
@Autowired(required = false)
private Cat cat;
@Autowired
private Dog dog;
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候,我们可以使用@Qualifier(value=“xxx”)去配合@Autowired的使用。指定一个唯一的bean对象注入
@Resource注解
public class People {
@Resource(name = "cat1111")
private Cat cat;
@Resource
private Dog dog;
}
小结:
@Resource和@Autoewired的区别:
都是用来自动装配的,都可以放在属性字段上
@Autowired通过bytype的方式实现
@Resource默认通过byname的方式实现,如果找不到名字,则通过bytype实现。如果两个都找不到的情况下,就报错!!
执行顺序不同:Autowired通过bytype的方式实现;Resource默认通过byname的方式实现