一、前言
上一篇博客(细说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 specified, <em>OR</em> logic is applied
* &a

本文详细介绍了Spring中如何通过注解进行包扫描过滤,包括按注解、类型和自定义过滤器的使用方法,并结合实例展示了FactoryBean的工作原理及其在容器中创建组件的独特之处。
&spm=1001.2101.3001.5002&articleId=80769291&d=1&t=3&u=9a94019f7f8a4b2491f4803c3588919f)
2142

被折叠的 条评论
为什么被折叠?



