spring组件扫描<context:component-scan/>使用详解

本文介绍了Spring框架中组件扫描的高级用法,包括如何利用正则表达式进行精确的类匹配,以及如何通过自定义过滤器增强扫描的灵活性。

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

关于spring自动检测组件的使用方式网上太多了,而且也不是我记录的重点,我想说下一点可能你还不知道的经验
我们知道如果不想在xml文件中配置bean,我们可以给我们的类加上spring组件注解,只需再配置下spring的扫描器就可以实现bean的自动载入。

下面是引用spring framework开发手册中的一段话“

Spring 2.5引入了更多典型化注解(stereotype annotations): @Component、@Service和 @Controller。 @Component是所有受Spring管理组件的通用形式; 而@Repository、@Service和 @Controller则是@Component的细化,用来表示更具体的用例(例如,分别对应了持久化层、服务层和表现层)。也就是说, 你能用@Component来注解你的组件类, 但如果用@Repository、@Service 或@Controller来注解它们,你的类也许能更好地被工具处理,或与切面进行关联。例如,这些典型化注解可以成为理想的切入点目标。当然,在Spring Framework以后的版本中, @Repository、@Service和 @Controller也许还能携带更多语义。如此一来,如果你正在考虑服务层中是该用 @Component还是@Service, 那@Service显然是更好的选择。同样的,就像前面说的那样, @Repository已经能在持久化层中进行异常转换时被作为标记使用了。”



下面是网上目前关于组件扫描最详细的介绍

Spring applicationContext.xml的<context:component-scan>標籤用途比我想像的還要實用。而且後來才知道,有了<context:component-scan>,另一個<context:annotation-config/>標籤根本可以移除掉,因為被包含進去了。原本我survery Spring3通常只配置成<context:component-scan base-package="com.foo.bar"/>,意即在base-package下尋找有@Component和@Configuration的target Class。而現在如下的飯粒:

<context:component-scan base-package="com.foo" use-default-filters="false">
<context:include-filter type="regex" expression="com.foo.bar.*Config"/>
<context:include-filter type="regex" expression="com.foo.config.*"/>
</context:component-scan>

  <context:component-scan>提供兩個子標籤:<context:include-filter>和<context:exclude-filter>各代表引入和排除的過濾。而上例把use-default-filters屬性設為false,意即在base-package所有被宣告為@Component和@Configuration等target Class不予註冊為bean,由filter子標籤代勞。

  filter標籤在Spring3有五個type,如下:
Filter Type Examples Expression Description
annotation org.example.SomeAnnotation 符合SomeAnnoation的target class
assignable org.example.SomeClass 指定class或interface的全名
aspectj org.example..*Service+ AspectJ語法
regex org\.example\.Default.* Regelar Expression
custom org.example.MyTypeFilter Spring3新增自訂Type,實作org.springframework.core.type.TypeFilter

  所以上例用的regex就有個語病,com.foo.config.* 可以找到com.foo.config.WebLogger,但也可以找到com1fool2config3abcde,因為小數點在Regex是任意字元,是故要用\.把小數點跳脫為佳。(2010/3/15補充:但要使用\.方式,其use-default-filters不能為false,否則抓不到,感覺是Bug)

  Spring3提供豐富的Filter支援,有益配置策略,不需面臨Configuration Hell,比如Regex的com\.foo\.*\.action\.*Config,這樣就可以找到com.foo package下所有action子package的*Config的target class。



我按他的例子,配置了我自己的如下:
<context:component-scan base-package="com.xhlx.finance.budget" >
<context:include-filter type="regex" expression="com.lee.finance.budget.service.*"/>
<context:include-filter type="regex" expression="com.lee.finance.budget.security.*"/>
</context:component-scan>
但是死活扫描不到,网上又没有更好的讲解,没办法只好自己试,改成
<context:component-scan base-package="com.xhlx.finance.budget" >
<context:include-filter type="regex" expression="com.lee.finance.budget.*"/>
</context:component-scan>
这样连没有加注解的类也扫描并实例化,结果报错,因为有的类根本就没有默认的构造函数不能实例化,能不报错吗
改成
<context:component-scan base-package="com.xhlx.finance.budget" >
<context:include-filter type="regex" expression="com\.lee\.finance\.budget\.service.*"/>
</context:component-scan>问题依旧
<context:component-scan base-package="com.xhlx.finance.budget" >
<context:include-filter type="regex" expression="com.lee.finance.budget.service.TestService"/>
</context:component-scan>
嘿,这次可以了,写全限定名就可以,表达式却不行,但是如果我有成千上百个还得一个一个这样配置啊?不行,继续研究,我想有个base-package的配置,从表面意思来看这是个“基本包”,是否表示下面的过滤路径是基于这个包的呢?于是试着改成
<context:component-scan base-package="com.xhlx.finance.budget" >
<context:include-filter type="regex" expression=".service.*"/>
</context:component-scan>
嘿,行了。看来,别人写的东西虽然能给你很多帮助,但也不一定全对啊,我希望每个人都坚持分享实践出来的东西,而不是人云亦云。

转自:http://blog.sina.com.cn/s/blog_5114d71d0100rk7b.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、付费专栏及课程。

余额充值