一、前言
上一篇博客(细说Spring——IoC详解(注解驱动开发之Bean的注入))中简单的介绍了将组件注入容器的三种方法,这次我们就了解一下如何在包扫描时将不想要的组件排除,或者只添加特定的组件,然后我们学习一下FactoryBean的作用,不知道FactoryBean的可以参考一下:细说Spring——IoC详解(FactoryBean、方法注入和方法替换)。
二、包扫描的过滤
使用@ComponentScan
指定要扫描的包,和使用xml
配置的包扫描大致类似使用excludeFilters
属性添加排除的组件,使用includeFilters
属性添加只要的组件,但是要使includeFilters
生效,必须先将useDefaultFilters
属性设置为false
,和xml
配置类似,如果使用的是jdk8
以上的版本,可以定义多个@ComponentScan
,如果jdk8
以下的版本,可以使用@ComponentScans
,来装多个@ComponentScan
达到相同的效果。
下面我们主要看一下怎么添加excludeFilters
和includeFilters
属性,我们先看一下这两个属性的源码是什么:
Filter[] includeFilters() default {};
/**
* Specifies which types are not eligible for component scanning.
* @see #resourcePattern
*/
Filter[] excludeFilters() default {};
我们可以看到这个个属性的参数都是Filter
数组,这里的Filter
是在@ComponentScan
包里的一个内部注解,我们看一下源码:
@Retention(RetentionPolicy.RUNTIME)
@Target({})
@interface Filter {
/**
* The type of filter to use.
* <p>Default is {@link FilterType#ANNOTATION}.
* @see #classes
* @see #pattern
*/
FilterType type() default FilterType.ANNOTATION;
/**
* Alias for {@link #classes}.
* @see #classes
*/
@AliasFor("classes")
Class<?>[] value() default {};
/**
* The class or classes to use as the filter.
* <p>The following table explains how the classes will be interpreted
* based on the configured value of the {@link #type} attribute.
* <table border="1">
* <tr><th>{@code FilterType}</th><th>Class Interpreted As</th></tr>
* <tr><td>{@link FilterType#ANNOTATION ANNOTATION}</td>
* <td>the annotation itself</td></tr>
* <tr><td>{@link FilterType#ASSIGNABLE_TYPE ASSIGNABLE_TYPE}</td>
* <td>the type that detected components should be assignable to</td></tr>
* <tr><td>{@link FilterType#CUSTOM CUSTOM}</td>
* <td>an implementation of {@link TypeFilter}</td></tr>
* </table>
* <p>When multiple classes are spe