Skip to content

Latest commit

 

History

History
44 lines (35 loc) · 2.41 KB

File metadata and controls

44 lines (35 loc) · 2.41 KB

3.10.4 使用过滤器自定义扫描

默认情况下,使用@Component@Repository@Service@Controller注解的类或者注解为@Component的自定义注解的类才能被检测为候选组件。 但是,你可以通过应用自定义过滤器来修改和扩展此行为。 将它们添加为@ComponentScan注解的* includeFilters excludeFilters 参数(或作为component-scan元素的 include-filter exclude-filter *子元素)。 每个过滤器元素需要typeexpression属性。 下表介绍了过滤选项。

Table 3.5. 过滤器类型

过滤器类型 表达式示例 描述
annotation (default) org.example.SomeAnnotation 目标组件类级别的注解
assignable org.example.SomeClass 目标组件继承或实现的类或接口

| | aspectj | org.example..*Service+ | 用于匹配目标组件的AspecJ类型表达式 | | regex | org\.example\.Default.* |用于匹配目标组件类名的正则表达式 | | custom | org.example.MyTypeFilter |org.springframework.core.type.TypeFilter接口的自定义实现 |

以下示例显示了忽略所有@Repository注解,并使用带有“stub”的Repository代替:

@Configuration
   @ComponentScan(basePackages = "org.example",
   		includeFilters = @Filter(type = FilterType.REGEX, pattern = ".*Stub.*Repository"),
   		excludeFilters = @Filter(Repository.class))
   public class AppConfig {
   	...
   }

或者使用XML形式配置:

<beans>
	<context:component-scan base-package="org.example">
		<context:include-filter type="regex"
				expression=".*Stub.*Repository"/>
		<context:exclude-filter type="annotation"
				expression="org.springframework.stereotype.Repository"/>
	</context:component-scan>
</beans>
[Note]
你还可以通过在注解上设置useDefaultFilters = false或通过use-default-filters =“false”作为<component-scan />元素的属性来禁用默认过滤器。 这将不会自动检测带有@Component@Repository,@Service@Controller, or @Configuration注解的类.