为了减少xml配置,Spring提供了自动检测与自动装配的方式。
自动检测
需要两步骤:
1. 在xml中,通过配置 < context:component-scan>来启用自动检测功能;
2. 在需要自动检测的Bean使用特殊的注解进行适当的标注,这些注解包括:
- @Componnet:通用的构造性注解,标识该类为Spring组件
- @Controller:标识将该类定义为Spring MVC controller
- @Repository:标识将该类定义为数据仓库(dao)
- @Service:标识将该类定义为服务
- 使用@Component标注的任意自定义注解,事实上,@Controller,@Repository,@Service也是使用@Component标注的注解
过滤组件扫面
< context:component-scan>可以通过< context:include-filter>和< context:exclude-filter>两个子元素来调整扫描策略,这两个子元素包含一个type和expression的属性,描述如下:
过滤器属性 | 描述 |
---|---|
annotation | 扫描指定注解所标注的那些类 |
assignable | 扫描派生于expression属性指定类型的那些类 |
aspectj | 扫描与expression属性所指定 |