Spring组件扫描使用详解

 

1.若是不想在xml文件中配置bean,咱们能够给咱们的类加上spring组件注解,只需再配置下spring的扫描器就能够实现bean的自动载入。<!-- 注解注入 -->spring

<context:annotation-config></context:annotation-config>express

<context:component-scan base-package="com.liantuo.hotel.common.service.impl" />app

<context:component-scan base-package="com.liantuo.hotel.common.dao.ibatis" />工具

<context:component-scan base-package="com.liantuo.hotel.app.dao.ibatis" />spa

<context:component-scan base-package="com.liantuo.hotel.app.service" />.net

<context:component-scan base-package="com.liantuo.hotel.app.service.ibatis" />code

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

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已经能在持久化层中进行异常转换时被做为标记使用了。”xml

3.有了<context:component-scan>,另外一个<context:annotation-config/>标签根本能够移除掉,由于已经被包含进去了。ip

4.<context:component-scan>提供两个子标签:<context:include-filter>和<context:exclude-filter>各表明引入和排除的过滤。

如:<context:component-scan base-package="com.xhlx.finance.budget" >

<context:include-filter type="regex" expression=".service.*"/>
</context:component-scan>

5.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
相关文章
相关标签/搜索