11 .通过注解配置Bean

配置Bean除了基于XML文件的形式,还可以基于注解的方式(基于注解配置Bean&基于注解装配Bean的属性)

在ClassPath中扫描组件

  • 组件扫描(component scanning):Spring能够从classpath下自动扫描侦测和实例化具有特定注解的组件

  • 特定组件包括:

    • @Component:基本注解,标识了一个受Spring管理的组件
    • @Respository:标识永久层组件
    • @Service:标识服务层(业务层)组件
    • @Controller:标识表现层组件
  • 对于扫描到的组件,Spring有默认的命名策略:通过非限定类名,第一个字母小写.也可以在注解中通过value属性值标识组件的名称

  • 当在组件上使用了特定的注解之后,还需要在Spring的配置文件中声明<context:component-scan>:

    • base-package属性指定一个需要扫描的基类包,Spring容器将会扫描这个基类包里及其子包中的所有类

    • 当需要扫描多个包时,可以使用逗号分隔

    • 如果仅希望扫描特定的类而非基类包下的所有类,可使用resource-patten属性过滤特定的类,示例:

      1
      2
      3
      <context:component-scan
      base-package="com.swzdl.spring.beans"
      resource-patten="autowire/*.class"/>
  • <context:include-filter>子节点表示要包含的目标类

  • <context:exclude-filter>子节点表示要排除在外的目标类

  • <context:component-scan>下可以拥有若干个<context:include-filter><context:exclude-filter>子节点

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×