美文网首页
spring学习11(注解方式配置bean)

spring学习11(注解方式配置bean)

作者: 又是那一片天 | 来源:发表于2017-07-25 12:01 被阅读0次
组件扫描 Spring能够从classPath下自动扫面,侦测和实例化具有特点注解的组件
特定组件包括:(标识在类上)
  • @Component 基本注解,标识一个受spring管理的组件
  • @Repository 标识持久层组件
  • @Service 标识服务层(业务层)组件
  • @Controller 标识表现层组件
对于扫描到的组件,spring有默认的命名规则:使用非限定类名,第一个字母小写,也可以通过value属性标识组件的名称

代码:
在note包下:

package note;
import org.springframework.stereotype.Component;

@Component("testPojo")
public class TestPojo {

}

配置文件:

<context:component-scan base-package="note"></context:component-scan> 

配置文件的过滤

指定扫描的包 扫描这个包下的所有子包
<context:component-scan base-package="note"></context:component-scan> 
使用属性resource-pattern 过滤只扫描指定的类
<!--resource-pattern 过滤只扫描指定的类 -->
<context:component-scan base-package="note" resource-pattern="son/*.class"></context:component-scan> 

使用文件的过滤使用:context:component-scan 子节点
  • context:exclude-filte:指定排除那些组件

  • context:include-filter:指定只包含那些组件

它们都有共同的属性 type 来指定使用什么方式来排除或包含
  • type="annotation" 根据注解
  • type="assignable" 根据接口或者类

共同属性 expression指定目标注解 或 类

  • context:exclude-filter指定排除那些组件:子节点的属性 type="annotation"根据注解不包含 expression属性指定的
    <!-- context:exclude-filter指定排除那些组件:子节点的属性 type="annotation"根据注解不包含  expression属性指定的 -->
<context:component-scan base-package="note">
        <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Component" />
</context:component-scan> 

  • context:exclude-filter指定排除那些组件:子节点的属性 type="assignable"根据接口或者类型不包含 expression属性指定的
<!-- context:exclude-filter指定排除那些组件:子节点的属性 type="assignable"根据接口或者类型不包含 expression属性指定的-->
     <context:component-scan base-package="note">
        <context:exclude-filter type="assignable"
            expression="note.son.TestPojoA" />
    </context:component-scan> 
  • context:include-filter指定只包含那些组件: 去掉默认filter只是用指定的filter use-default-filters="false"
<!-- context:include-filter指定只包含那些组件: 去掉默认filter只是用指定的filter use-default-filters="false" -->
     <context:component-scan base-package="note " use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Component"/>
    </context:component-scan>
注意指定指定只包含时:去掉默认filter只是用指定的filter use-default-filters="false"

相关文章

网友评论

      本文标题:spring学习11(注解方式配置bean)

      本文链接:https://www.haomeiwen.com/subject/fxdwkxtx.html