分享

Spring 自动扫描 注解驱动 Bean 管理

 CevenCheng 2010-09-25
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www./schema/beans"
xmlns:xsi="http://www./2001/XMLSchema-instance" xmlns:jee="http://www./schema/jee"
xmlns:tx="http://www./schema/tx" xmlns:context="http://www./schema/context"
xmlns:aop="http://www./schema/aop" 
xsi:schemaLocation="http://www./schema/beans http://www./schema/beans/spring-beans-2.5.xsd 
http://www./schema/context http://www./schema/context/spring-context-2.5.xsd
http://www./schema/tx http://www./schema/tx/spring-tx-2.5.xsd 
http://www./schema/aop http://www./schema/aop/spring-aop-2.5.xsd
http://www./schema/jee http://www./schema/jee/spring-jee-2.5.xsd">

<description>Spring配置文件</description>

<!-- 使用annotation 自动注册bean,并检查@Required,@Autowired的属性已被注入 -->
<context:annotation-config /> 
<context:component-scan base-package="test.haohui">
<!-- <context:exclude-filter type="regex" expression="test\.haohui\.resl\.controller\..*" />  --> <!--exclude-filter 排除在外的 -->
<context:include-filter type="regex" expression="test\.haohui\.resl\.controller\..*" />           <!--exclude-filter 包含在内的 -->
<context:include-filter type="aspectj" expression="test.haohui.resl.service.*" />     
</context:component-scan>
</beans>

扫描过滤方式
过滤器类型说明
注释假如 com.baobaotao.SomeAnnotation 是一个注释类,我们可以将使用该注释的类过滤出来。
类名指定通过全限定类名进行过滤,如您可以指定将 com.baobaotao.Boss 纳入扫描,而将 com.baobaotao.Car 排除在外。
正则表达式通过正则表达式定义过滤的类,如下所示: com\.baobaotao\.Default.*
AspectJ 表达式通过 AspectJ 表达式定义过滤的类,如下所示: com. baobaotao..*Service+

下面是一个简单的例子:

<context:component-scan base-package="com.baobaotao">
    <context:include-filter type="regex" 
        expression="com\.baobaotao\.service\..*"/>
    <context:exclude-filter type="aspectj" 
        expression="com.baobaotao.util..*"/>
</context:component-scan>

值得注意的是 <context:component-scan/> 配置项不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和CommonAnnotationBeanPostProcessor),因此当使用 <context:component-scan/> 后,就可以将 <context:annotation-config/> 移除了。

默认情况下通过 @Component 定义的 Bean 都是 singleton 的,如果需要使用其它作用范围的 Bean,可以通过 @Scope 注释来达到目标,如以下代码所示:

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多