Bean的自动装配
==Spring会在上下文中自动寻找,并自动给bean装配属性==
三种方式:
1、在xml中显示的配置
2、在Java中显示配置
3、隐式的自动装配bean
1、测试
环境搭建:一个人有两个宠物Demo
2、byName自动装配
<bean id="cat" class="com.sw.pojo.Cat"/>
<bean id="dog" class="com.sw.pojo.Dog"/>
<!--byName:会自动在容器上下文中查找和自己对象中(Person)set方法后面的值对应的beanid-->
<bean id="person" class="com.sw.pojo.Person" autowire="byName">
<property name="name" value="孙笑川"/>
</bean>
3、byType自动装配
<bean id="cat2" class="com.sw.pojo.Cat"/>
<bean id="dog1" class="com.sw.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找,和自己对象中(Person)set方法后面的值对应的beanid
byType:会自动在容器上下文中查找,和自己对象属性类型相对应的bean
-->
<bean id="person" class="com.sw.pojo.Person" autowire="byType">
<property name="name" value="孙笑川"/>
</bean>
注:
- byName:需要保证所有bean的id唯一,且这个bean需要和自动注入的属性的set方法的值一致
- byType:需要保证所有bean的class唯一,且这个bean需要和自动注入的属性的类型一致
4、使用注解实现自动装配
1、导入context约束
2、开启注解
<?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>
@Autowired
直接在属性上用即可,也可以在set方法上使用
@Nullable //字段标记了这个注解,说明这个字段可以为null
@Autowired(required = false) //如果显示的定义Autowired的required属性为fasle,说明这个对象可以为空
//默认为true 不允许为空
public @interface Autowired {
boolean required() default true;
}
注:如果@Autowired自动装配的环境比较复杂,无法通过一个@Autowired注解完成的时候,
可以使用@Qualifier(value = "xxx"),指定一个唯一的bean对象
public class Person {
private String name;
@Autowired
private Dog dog;
@Autowired
@Qualifier(value = "cat")
private Cat cat;
}
@Resource
public class Person {
private String name;
@Resource(name = "cat1212")
private Dog dog;
@Resource
private Cat cat;
}
小结:
@Autowired与@Resource的区别
- 都是用来自动装配的
- @Autowired 通过byType的方式实现,且对象必须存在
- @Resource 默认通过byName的方式实现,如果找不到对应的bean id,则通过byType实现
评论 (0)