细说Spring——IoC详解(注解驱动开发之包扫描过滤和FactoryBean)

本文详细介绍了Spring中如何通过注解进行包扫描过滤,包括按注解、类型和自定义过滤器的使用方法,并结合实例展示了FactoryBean的工作原理及其在容器中创建组件的独特之处。
摘要由CSDN通过智能技术生成
一、前言

上一篇博客(细说Spring——IoC详解(注解驱动开发之Bean的注入))中简单的介绍了将组件注入容器的三种方法,这次我们就了解一下如何在包扫描时将不想要的组件排除,或者只添加特定的组件,然后我们学习一下FactoryBean的作用,不知道FactoryBean的可以参考一下:细说Spring——IoC详解(FactoryBean、方法注入和方法替换)

二、包扫描的过滤

使用@ComponentScan指定要扫描的包,和使用xml配置的包扫描大致类似使用excludeFilters属性添加排除的组件,使用includeFilters属性添加只要的组件,但是要使includeFilters生效,必须先将useDefaultFilters属性设置为false,和xml配置类似,如果使用的是jdk8以上的版本,可以定义多个@ComponentScan,如果jdk8以下的版本,可以使用@ComponentScans,来装多个@ComponentScan达到相同的效果。

下面我们主要看一下怎么添加excludeFiltersincludeFilters属性,我们先看一下这两个属性的源码是什么:

    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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值