即使context:annotation-config有助于帮助我们完全消除Spring配置中的
使用还有另外一个技巧:context:component-scan。它可以完成context:annotation-config一样的工作,还允许自动检测Bean和定义Bean。使用自动检测,需要context:component-scan来替代context:annotation-config元素。
1 | <context:component-scan base-package="com.websystique.spring" /> |
context:component-scan元素会扫描指定包及其所有的子包。并查找出能够自动注册为Spring Bean的类。这需要构造型(stereotype)进行注解。
为自动检测标注Bean
特殊注解如下:
- @Component-通用的构造型注解,标识该类为spring的组件
- @Controller-标识将该类定义为 Spring MVC controller
- @Repository-标识将该类定义为数据仓库
- @Service-标示将该类定义为服务
Bean的ID默认为无限定类名。例如:Guitar Bean的ID为guitar。
过滤组件扫描
通过为context:component-scan配置context:include-filter或者context:exclude-filter子元素,我们可以随意调整扫描策略。
如果试用了第三方的Instrument的子类实现,或许我们都没有源码的访问权限来添加注解,这时候就可以使用过滤器来解决。
context:include-filter告知哪些类需要注册为Spring Bean
context:exclude-filter告知哪些类不需要注册为Spring Bean