spring整理

来源:互联网 发布:济南网站系统优化 编辑:程序博客网 时间:2024/05/21 09:54

想要在工程中使用spring的注解,首先需要正确的注册注解处理器:

  • 注册bean的形式
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

这种注册bean的形式在工作中使用比较少,因为想要使用不同的注解你需要注册不同的注解处理起的bean。

  • 命名空间 < context:annotation-config />
<context:annotation-config />

这种形式相对于上面那种形式相对好一些,spring在xml中这行配置,会隐式的向Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。

  • 命名空间 < context:component-scan />
<context:component-scan base-package="com.XXX.XXX" />

该配置项其实也包含了自动注入上述processor的功能,因此当使用< context:component-scan />后,即可将< context:annotation-config />省去。
base-package 属性指定了需要扫描的类包,类包及其递归子包中所有的类都会被处理。还允许定义过滤器将基包下的某些类纳入或排除。

下面是看到的一些注解过滤方式:

• Spring 支持以下4 种类型的过滤方式:

  • 注解 org.example.SomeAnnotation 将所有使用SomeAnnotation 注解的类过滤出来  • 类名指定 org.example.SomeClass 过滤指定的类  • 正则表达式 com.kedacom.spring.annotation.web..* 通过正则表达式过滤一些类  • AspectJ 表达式 org.example..*Service+ 通过AspectJ 表达式过滤一些类

• 正则表达式的过滤方式举例:

<context:component-scanbase-package="com.casheen.spring.annotation">    <context:exclude-filtertype="regex" expression="com.casheen.spring.annotation.web..*"/></context:component-scan>

• 注解的过滤方式举例:

<context:component-scan base-package="com.netqin" >    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>    <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/></context:component-scan>
原创粉丝点击