自动装配
自动装配说明
-
自动装配是使用spring满足bean依赖的一种方法
-
spring会在应用上下文中为某个bean寻找其依赖的bean。
Spring中bean有三种装配机制,分别是:
-
在xml中显式配置;
-
在java中显式配置;
-
隐式的bean发现机制和自动装配。【重点】
Spring的自动装配需要从两个角度来实现,或者说是两个操作:
-
组件扫描(component scanning):spring会自动发现应用上下文中所创建的bean;
-
自动装配(autowiring):spring自动满足bean之间的依赖,也就是我们说的IOC/DI;
组件扫描和自动装配组合发挥巨大威力,使得显示的配置降低到最少。
推荐不使用自动装配xml配置 , 而使用注解
byName 按照名称
byType 按照类型
<context:annotation-config/>
<bean id="cat" class="com.gh.pojo.Cat"/>
<bean id="dog" class="com.gh.pojo.Dog"/>
<!--autowire自动装配
byName:会自动在容器上下文中查找,和自己对象set方法后面的值对应的 bean id !(保证id唯一)
set 后面的名字的 id 相同就可以注入
byType:会自动在容器上下文中查找,和自己对象属性类型相同的bean !(不需要id,保证bean的class唯一)
保证 类型全局唯一 可以省略id
-->
<bean id="people" class="com.gh.pojo.People" autowire="byName">
<property name="name" value="王五"/>
<!-- <property name="cat" ref="cat"/>-->
<!-- <property name="dog" ref="dog"/>-->
</bean>
使用注解注册
1、@Autowired
-
@Autowired是按类型自动转配的,不支持id匹配。
2、@Qualifier
-
@Autowired是根据类型自动装配的,加上@Qualifier则可以根据byName的方式自动装配
-
@Qualifier不能单独使用
3、@Resource
-
@Resource如有指定的name属性,先按该属性进行byName方式查找装配;
-
其次再进行默认的byName方式进行装配;
-
如果以上都不成功,则按byType的方式自动装配。
-
都不成功,则报异常
@Resource和@Autowired的区别:
都是用来自动装配的,都可以放在属性字段上
@Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
@Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
执行顺序不同:@Autowired通过byType的方式实现。
public class People1 {
//Autowired注解注入方式,自动装配当有多个对像的时候可以使用@Qualifier来指定对象
@Autowired
@Qualifier(value = "cat1234")
private Cat cat;
//如果显示定义了Autowired的required属性为false,说明这个对象可以为nuLl,否则不允许为空
//@Resource(name="dog")绑定也可以自动装配但是没有@Autowired智能
// @Autowired(required = false)
@Resource( name = "dog123")
private Dog dog;
private String name;
2、bean,xml 【开启注解驱动】
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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.gh.pojo1.Cat"/>
<bean id="dog123" class="com.gh.pojo1.Dog"/>
<bean id="people1" class="com.gh.pojo1.People1"/>
</beans>
使用注解开发
1、配置扫描哪些包下的注解
<!--指定注解扫描包-->
<context:component-scan base-package="com.kuang.pojo"/>
全部注解
编写类,增加注解
@Component -----类
@Controller:web层 -----类
@Service:service层 -----类
@Repository:dao层 -----类
属性
@Value ----属性、set方法
自动装配
@Autowired
@Qualifier
@Resource
作用域
@scope
- singleton:单例模式 默认
- prototype:多例模式
配置类
@Configuration -----类
@ComponentScan 扫描 -----类
@Import() 导入合并其他配置类
@Bean ---方法 的返回值就Bean的类型,方法名就是bean的id