学习目标:通过注解配置Bean
注解的前提:
组件扫描(component scanning): Spring 能够从 classpath 下自动扫描, 侦测和实例化具有特定注解的组件.
特定组件包括:
@Component: 基本注解, 标识了一个受 Spring 管理的组件
@Respository: 标识持久层组件
@Service: 标识服务层(业务层)组件
@Controller: 标识表现层组件
(可以混用。。。。)
对于扫描到的组件, Spring 有默认的命名策略: 使用非限定类名, 第一个字母小写. 也可以在注解中通过 value 属性值标识组件的名称。
例如UserService —->userService
当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 :
base-package 属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.
当需要扫描多个包时, 可以使用逗号分隔.
context:component-scan配置说明
<context:component-scan
base-package="com.atguigu.spring.beans.annotation"
resource-pattern="repository/*.class">
</context:component-scan>
base-package 指定Spring IOC容器扫描的包
resource-pattern指定扫描的资源
如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern 属性过滤特定的类,示例:
<context:include-filter>子节点表示要包含的目标类
<context:exclude-filter>子节点表示要排除在外的目标类和use-default-filters="false"配合使用
< context:component-scan> 下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点
①annotation方式 只包含com.atguigu.spring.beans.annotation包下的Repository注解
<context:component-scan base-package="com.atguigu.spring.beans.annotation" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
②annotation方式 排除com.atguigu.spring.beans.annotation包下的Repository注解
<context:component-scan base-package="com.atguigu.spring.beans.annotation" >
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
</context:component-scan>
③assignable方式排除某个特定包下类的注解
<context:component-scan base-package="com.atguigu.spring.beans.annotation">
<context:exclude-filter type="assignable" expression="com.atguigu.spring.beans.annotation.repository.UserRepository"/><!-- 排除UserRepostory类的注解--!>
</context:component-scan>
④assignable方式只包含某个特定包下类的注解
<context:component-scan base-package="com.atguigu.spring.beans.annotation" use-default-filters="false">
<context:include-filter type="assignable" expression="com.atguigu.spring.beans.annotation.repository.UserRepository"/>
</context:component-scan>
则IOC容器只管理UserRepository这个bean其他不会管理