自动检测:比自动装配更近一步,让Spring能够自动识别哪些类需要被装配成Spring Bean,从而减少<bean>元素的使用。
使用<context:annotation-config>有助于完全消除Spring配置中的<property>和<constructor-arg>元素,我们仍需要使用<bean>元素显示定义Bean。
即使使用基于Java的配置,我们虽然避免了写大量的xml元素,但是我们仍需要在@Configuration注解的类中使用大量的@Bean注解来注入Bean。
为了解决这一问题,Spring允许使用<context:component-scan>元素,它除了完成与<context:annotation-config>一样的工作,还允许自动检测Bean和定义Bean。这意味着不使用<bean>元素,Spring应用中的大多数(或者所有)Bean都能够实现定义和装配。
为了配置Spring自动检测,需要使用<context:component-scan>元素来代替<context:annotation-config>元素。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
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-4.0.xsd
">
<context:component-scan base-package="pray.wang.java"></context:component-scan>
</beans>
<context:component-scan>元素会扫描指定包及其所有子包,并查找出能够自动注册为Spring Bean的类。base-package属性标识了<context:component-scan>元素所扫描的包。
为自动检测标注Bean
默认情况下,<context:component-scan>查找使用构造型注解所标注的类,这些特殊的注解如下:
- @Componet:通用的构造型注解,标识该类为Spring组件
- @Controller:标识将该注解定义为Spring MVC controller
- @Repository:标识将该类定义为数据仓库
- @Service:标识将该注解定义为服务
过滤组件扫描
在如何扫描来获得候选Bean方面,<context:component-scan>非常灵活。通过为<context:component-scan>配置<context:include-filter>和/或者<context:exclude-filter>子元素,我们可以随意调整扫描行为。
使用<context:include-filter>可以替换掉基于注解的组件扫描策略,从而实现将一些无法访问的类(如第三方Jar包)注入到Spring中。
常用的过滤器类型:
过滤器类型 | 描述 |
---|---|
annotation | 过滤器扫描和使用指定注解所标注的那些类。通过experssion属性指定要扫描的注解 |
assignable | 过滤器扫描派生于expression属性所指定类型的那些类 |
aspectj | 过滤器扫描与expression属性所指定的AspectJ表达式多匹配的那些类。 |
custom | 使用自定义的org.springframework.core.type.TypeFilter实现类,该类由expression属性指定 |
regex | 过滤器扫描类的名称与expression属性指定的正则表达式所匹配的那些类。 |
网友评论