-
spring 能够从classpath下
自动扫描
,侦测
和实例化
具有特定注解的组件(Java类)。
组件包括:4个注解
-
@Component
基本注解,标识一个受spring IOC容器管理的一个组件。 -
@Respository
标识持久层 -
@Service
标识服务层(业务层) -
@Controller
标识控制层(表现层)
对于扫描到的组件,spring有默认的命名策略:
使用类名且第一个字母小写
。
也可以在注解中通过
value属性
标识组件名称。
当在组件类上使用了特定的注解之后, 还需要在 Spring 的配置文件中声明 <context:component-scan>
base-package
属性指定一个需要扫描的基类包,Spring 容器将会扫描这个基类包里及其子包中的所有类.
当需要扫描多个包时, 可以使用逗号
分隔.
如果仅希望扫描特定的类而非基包下的所有类,可使用 resource-pattern
属性过滤特定的类
<context:component-scan base-package="com" resource-pattern="test/*.class"/>
<context:include-filter> 子节点表示要包含的目标类
<context:exclude-filter> 子节点表示要排除在外的目标类
<context:component-scan>
下可以拥有若干个 <context:include-filter> 和 <context:exclude-filter> 子节点
<!-- resource-pattern 指定扫描特定包下的类。resource-pattern="annotation/service/impl/*.class" -->
<context:component-scan base-package="com/igeek/lesson2" use-default-filters="false" >
<!-- type共五种,annotation注解,assignable所有继承或实现xxx的类。 aspectj ,regex , custom -->
<!-- <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> -->
<context:include-filter type="assignable" expression="com.igeek.lesson2.annotation.service.UserService"/>
</context:component-scan>