在Java中有一个不成名的规定:约束 > 注解 > XML配置 > 代码
使用注解标识组件,注解是使用在类上面标识


装配对象的四个注解
| 注解 | 描述 |
|---|---|
| @Component | 标识一个受Spring IOC容器管理的普通组件 |
| @Repository | 标识一个收Spring IOC容器管理的持久化层组件 |
| @Service | 标识一个受Spring IOC容器管理的业务逻辑层组件 |
| @Controller | 标识一个受Spring IOC容器管理的表述层控制器组件 |
使用注解步骤
<!--组件扫描
base-package:设置扫描注解包名(当前包以及子包)-->
<context:component-scan base-package="com.zyh"></context:component-scan>
@Autowired注解
作用:自动装配对象中的属性
装配原理:反射机制

装配方式:
先按照byType进行匹配
报错 org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'deptService': Unsatisfied dependency expressed through field 'deptDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.zyh.dao.DeptDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

再按照byName进行唯一筛选
@Autowired中required属性



组件被上述注解标识后,还需要通过Spring进行扫描才能侦测到
当前包及其子包都会被扫描到

<!--组件扫描
base-package:设置扫描注解包名(当前包以及子包)
annotation是设置注解的全路径
assignable是设置类的全路径-->
<context:component-scan base-package="com.zyh" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
<context:include-filter type="assignable" expression="com.zyh.controller.DeptController "/>
</context:component-scan>
如果我们不想扫描哪些包,我们就可以使用排除扫描
<!-- 排除扫描-->
<context:component-scan base-package="com.zyh">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
可以使用一个配置类来代替配置
①创建配置类
②在class上面添加注解

③使用AnnotationConfigApplicationContext容器对象

因为Spring提供了对Junit的集成,所以可以在测试类中直接注入IOC容器中的对象,使用此功能需要导入spring-tesxt-5.3.1.8jar
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.3.18</version>
<scope>test</scope>
</dependency>
