<context:component-scan>详解

本文深入解析Spring框架中&lt;context:component-scan&gt;元素的配置及应用,介绍其属性功能,包括扫描路径、注解激活、过滤机制等,并探讨Bean的ID生成策略和作用域配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

默认情况下,<context:component-scan>查找使用构造型(stereotype)注解所标注的类,如@Component(组件),@Service(服务),@Controller(控制器),@Repository(数据仓库)

我们具体看下<context:component-scan>的一些属性,以下是一个比较具体的<context:component-scan>配置

<context:component-scan base-package="com.wjx.betalot" <!-- 扫描的基本包路径 -->
                        annotation-config="true" <!-- 是否激活属性注入注解 -->
                        name-generator="org.springframework.context.annotation.AnnotationBeanNameGenerator"  <!-- Bean的ID策略生成器 -->
                        resource-pattern="**/*.class" <!-- 对资源进行筛选的正则表达式,这边是个大的范畴,具体细分在include-filter与exclude-filter中进行 -->
                        scope-resolver="org.springframework.context.annotation.AnnotationScopeMetadataResolver" <!-- scope解析器 ,与scoped-proxy只能同时配置一个 -->
                        scoped-proxy="no" <!-- scope代理,与scope-resolver只能同时配置一个 -->
                        use-default-filters="false" <!-- 是否使用默认的过滤器,默认值true -->
                                  >
            <!-- 注意:若使用include-filter去定制扫描内容,要在use-default-filters="false"的情况下,不然会“失效”,被默认的过滤机制所覆盖 -->                   
            <!-- annotation是对注解进行扫描 -->
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/> 
            <!-- assignable是对类或接口进行扫描 -->
            <context:include-filter type="assignable" expression="com.wjx.betalot.performer.Performer"/>
            <context:include-filter type="assignable" expression="com.wjx.betalot.performer.impl.Sonnet"/>
            
            <!-- 注意:在use-default-filters="false"的情况下,exclude-filter是针对include-filter里的内容进行排除 -->
            <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
            <context:exclude-filter type="assignable" expression="com.wjx.betalot.performer.impl.RainPoem"/>
            <context:exclude-filter type="regex" expression=".service.*"/> 

</context:component-scan>

以上配置注释已经很详细了,当然因为这些注释,你若是想复制去验证,你得删掉注释。我们具体再说明一下这些注释:

back-package:标识了<context:component-scan>元素所扫描的包,可以使用一些通配符进行配置

annotation-config:<context:component-scan>元素也完成了<context:annotation-config>元素的工作,开关就是这个属性,false则关闭属性注入注解功能

name-generator:这个属性指定你的构造型注解,注册为Bean的ID生成策略,这个生成器基于接口BeanNameGenerator实现generateBeanName方法,你可以自己写个类去自定义策略。这边,我们可不显示配置,它是默认使用org.springframework.context.annotation.AnnotationBeanNameGenerator生成器,也就是类名首字符小写的策略,如Performer类,它注册的Bean的ID为performer.并且可以自定义ID,如@Component("Joy").这边简单贴出这个默认生成器的实现。

public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        if (definition instanceof AnnotatedBeanDefinition) {
            String beanName = determineBeanNameFromAnnotation((AnnotatedBeanDefinition) definition);
            if (StringUtils.hasText(beanName)) {
                // Explicit bean name found.
                return beanName;
            }
        }
        // Fallback: generate a unique default bean name.
        return buildDefaultBeanName(definition, registry);
}

 

 Spring除了实现了AnnotationBeanNameGenerator生成器外,还有个org.springframework.beans.factory.support.DefaultBeanNameGenerator生成器,它为了防止Bean的ID重复,它的生成策略是类路径+分隔符+序号

 ,如com.wjx.betalot.performer.impl.Sonnet注册为Bean的ID是com.wjx.betalot.performer.impl.Sonnet#0,这个生成器不支持自定义ID,否则抛出异常。同样贴出代码,有兴趣的可以去看下。

public static String generateBeanName(
            BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)
            throws BeanDefinitionStoreException {

        String generatedBeanName = definition.getBeanClassName();
        if (generatedBeanName == null) {
            if (definition.getParentName() != null) {
                generatedBeanName = definition.getParentName() + "$child";
            }
            else if (definition.getFactoryBeanName() != null) {
                generatedBeanName = definition.getFactoryBeanName() + "$created";
            }
        }
        if (!StringUtils.hasText(generatedBeanName)) {
            throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " +
                    "'class' nor 'parent' nor 'factory-bean' - can't generate bean name");
        }

        String id = generatedBeanName;
        if (isInnerBean) {
            // Inner bean: generate identity hashcode suffix.
            id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition);
        }
        else {
            // Top-level bean: use plain class name.
            // Increase counter until the id is unique.
            int counter = -1;
            while (counter == -1 || registry.containsBeanDefinition(id)) {
                counter++;
                id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + counter;
            }
        }
        return id;
    }

 

resource-pattern:对资源进行筛选的正则表达式,这边是个大的范畴,具体细分在include-filter与exclude-filter中进行。

scoped-proxy: scope代理,有三个值选项,no(默认值),interfaces(接口代理),targetClass(类代理),那什么时候需要用到scope代理呢,举个例子,我们知道Bean的作用域scope有singleton,prototype,request,session,那有这么一种情况,当你把一个session或者request的Bean注入到singleton的Bean中时,因为singleton的Bean在容器启动时就会创建A,而session的Bean在用户访问时才会创建B,那么当A中要注入B时,有可能B还未创建,这个时候就会出问题,那么代理的时候来了,B如果是个接口,就用interfaces代理,是个类则用targetClass代理。这个例子出处:http://www.bubuko.com/infodetail-1434289.html。

scope-resolver:这个属性跟name-generator有点类似,它是基于接口ScopeMetadataResolver的,实现resolveScopeMetadata方法,目的是为了将@Scope(value="",proxyMode=ScopedProxyMode.NO,scopeName="")的配置解析成为一个ScopeMetadata对象,Spring这里也提供了两个实现,我们一起看下。首先是org.springframework.context.annotation.AnnotationScopeMetadataResolver中,

public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
        ScopeMetadata metadata = new ScopeMetadata();
        if (definition instanceof AnnotatedBeanDefinition) {
            AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
            AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(annDef.getMetadata(), this.scopeAnnotationType);
            if (attributes != null) {
                metadata.setScopeName(attributes.getAliasedString("value", this.scopeAnnotationType, definition.getSource()));
                ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
                if (proxyMode == null || proxyMode == ScopedProxyMode.DEFAULT) {
                    proxyMode = this.defaultProxyMode;
                }
                metadata.setScopedProxyMode(proxyMode);
            }
        }
        return metadata;
    }

 

对比一下org.springframework.context.annotation.Jsr330ScopeMetadataResolver中的实现:

public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
        ScopeMetadata metadata = new ScopeMetadata();
        metadata.setScopeName(BeanDefinition.SCOPE_PROTOTYPE);
        if (definition instanceof AnnotatedBeanDefinition) {
            AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
            Set<String> annTypes = annDef.getMetadata().getAnnotationTypes();
            String found = null;
            for (String annType : annTypes) {
                Set<String> metaAnns = annDef.getMetadata().getMetaAnnotationTypes(annType);
                if (metaAnns.contains("javax.inject.Scope")) {
                    if (found != null) {
                        throw new IllegalStateException("Found ambiguous scope annotations on bean class [" +
                                definition.getBeanClassName() + "]: " + found + ", " + annType);
                    }
                    found = annType;
                    String scopeName = resolveScopeName(annType);
                    if (scopeName == null) {
                        throw new IllegalStateException(
                                "Unsupported scope annotation - not mapped onto Spring scope name: " + annType);
                    }
                    metadata.setScopeName(scopeName);
                }
            }
        }
        return metadata;
    }

 

ps:scope-resolver与scoped-proxy只能配置一个,配置了scope-resolver后你要使用代理,可以配置@Scope总的proxyMode属性项

use-default-filters:是否使用默认的扫描过滤。

<context:include-filter> :用来告知哪些类需要注册成Spring Bean,使用type和expression属性一起协作来定义组件扫描策略。type有以下5种

过滤器类型描述
annotation过滤器扫描使用注解所标注的那些类,通过expression属性指定要扫描的注释
assignable过滤器扫描派生于expression属性所指定类型的那些类
aspectj过滤器扫描与expression属性所指定的AspectJ表达式所匹配的那些类
custom使用自定义的org.springframework.core.type.TypeFliter实现类,该类由expression属性指定
regex过滤器扫描类的名称与expression属性所指定正则表示式所匹配的那些类

 

 

 

 

 

 

 

要注意的是:若使用include-filter去定制扫描内容,要在use-default-filters="false"的情况下,不然会“失效”,被默认的过滤机制所覆盖

<context:exclude-filter>:与<context:include-filter> 相反,用来告知哪些类不需要注册成Spring Bean,同样注意的是:在use-default-filters="false"的情况下,exclude-filter是针对include-filter里的内容进行排除。

 

转载于:https://www.cnblogs.com/fightingcoding/p/component-scan.html

<?xml version="1.0" encoding="UTF-8"?> <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" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <!-- 对基本包进行注解扫描,开启注解 --> <context:component-scan base-package="com.esms"> <!-- 只对controller进行扫描 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- Spring的配置文件,这里主要配置和业务逻辑有关的 --> <!--=================== 数据源,事务控制,xxx ================ --> <!-- 加载数据库配置文件dbconfig.properties --> <context:property-placeholder location="classpath:db.properties" /> <!-- 加载数据库 --> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${datasource.connection.driver_class}"/> <property name="jdbcUrl" value="${datasource.connection.url}"/> <property name="user" value="${datasource.connection.username}"/> <property name="password" value="${datasource.connection.password}"/> <property name="minPoolSize" value="${datasource.connection.minPoolSize}"/> <!--连接池中保留的最大连接数。Default: 15 --> <property name="maxPoolSize" value="${datasource.connection.maxPoolSize}"/> <!--最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 --> <property name="maxIdleTime" value="${datasource.connection.maxIdleTime}"/> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 --> <property name="acquireIncrement" value="${datasource.connection.acquireIncrement}"/> <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements 属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。 如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 --> <property name="maxStatements" value="${datasource.connection.maxStatements}"/> <!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 --> <property name="maxStatementsPerConnection" value="${datasource.connection.maxStatementsPerConnection}"/> <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> <property name="initialPoolSize" value="${datasource.connection.initialPoolSize}"/> <!--每60秒检查所有连接池中的空闲连接。Default: 0 --> <property name="idleConnectionTestPeriod" value="${datasource.connection.idleConnectionTestPeriod}"/> <!--定义在从数据库获取新连接失败后重复尝试的次数。Default: 30 --> <property name="acquireRetryAttempts" value="${datasource.connection.acquireRetryAttempts}"/> <!--获取连接失败将会引起所有等待连接池来获取连接的线程抛出异常。但是数据源仍有效 保留,并在下次调用getConnection()的时候继续尝试获取连接。如果设为true,那么在尝试 获取连接失败后该数据源将申明已断开并永久关闭。Default: false --> <property name="breakAfterAcquireFailure" value="${datasource.connection.breakAfterAcquireFailure}"/> <!--因性能消耗大请只在需要的时候使用它。如果设为true那么在每个connection提交的 时候都将校验其有效性。建议使用idleConnectionTestPeriod或automaticTestTable 等方法来提升连接测试的性能。Default: false --> <property name="testConnectionOnCheckout" value="${datasource.connection.testConnectionOnCheckout}"/> <property name="checkoutTimeout" value="${datasource.connection.checkoutTimeout}"/> <property name="testConnectionOnCheckin" value="${datasource.connection.testConnectionOnCheckin}"/> <property name="automaticTestTable" value="${datasource.connection.automaticTestTable}"/> <property name="acquireRetryDelay" value="${datasource.connection.acquireRetryDelay}"/> <!--自动超时回收Connection--> <property name="unreturnedConnectionTimeout" value="${datasource.connection.unreturnedConnectionTimeout}"/> <!--超时自动断开--> <property name="maxIdleTimeExcessConnections" value="${datasource.connection.maxIdleTimeExcessConnections}"/> <property name="maxConnectionAge" value="${datasource.connection.maxConnectionAge}"/> </bean> <!--================== 配置和MyBatis的整合=============== --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis,mapper文件的位置 --> <property name="mapperLocations" value="classpath:mappers/*.xml"></property> </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描所有dao接口的实现,加入到ioc容器中 --> <property name="basePackage" value="com.esms.dao"></property> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean> <!-- 配置一个可以执行批量的sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> <!-- ===============事务控制的配置 ================ --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!--控制住数据源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!--配置事务增强,事务如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true" propagation="SUPPORTS"/> <tx:method name="list*" read-only="true" propagation="SUPPORTS"/> <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> <tx:method name="query*" read-only="true" propagation="SUPPORTS"/> <tx:method name="count*" read-only="true" propagation="SUPPORTS"/> <tx:method name="update*" read-only="false" propagation="REQUIRED"/> <tx:method name="insert*" read-only="false" propagation="REQUIRED"/> <tx:method name="save*" read-only="false" propagation="REQUIRED"/> <tx:method name="delete*" read-only="false" propagation="REQUIRED"/> <tx:method name="remove*" read-only="false" propagation="REQUIRED"/> <tx:method name="*" read-only="true" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:aspectj-autoproxy proxy-target-class="true"/> <!--开启基于注解的事务,使用xml配置形式的事务(必要主要的都是使用配置式) --> <aop:config> <!-- 切入点表达式 --> <!-- 需要修改包的扫描 --> <aop:pointcut expression="execution(* com.esms.service.impl.*.*(..))" id="txPoint" /> <!-- 配置事务增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint" /> </aop:config> <bean class="com.esms.exception.CustomExceptionResolver"/> </beans>
07-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值