天天看点

Spring注解之xml配置中的<context:component-scan />和<context:annotation-config/>

今天偶然看见项目中的applicationContext.xml配置文件,就想起来曾经学习的时候比较困惑一个问题:<context:component-scan />和<context:annotation-config/> 这两种注解配置到底有啥区别??。。其实到今天如果不是看帖子估计我还是迷迷糊糊的,不喜欢探究的程序员不是好java工程师。。

Spring注解之xml配置中的&lt;context:component-scan /&gt;和&lt;context:annotation-config/&gt;

首先从<context:annotation-config/>说起

<context:annotation-config/>篇

他的作用是式地向 Spring 容器注册

AutowiredAnnotationBeanPostProcessor、
CommonAnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
RequiredAnnotationBeanPostProcessor 
           

注册这4个 BeanPostProcessor的作用,就是为了你的系统能够识别相应的注解。说白了,如果你想使用@Autowired注解,那么就必须事先在 spring 容器中声明

<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/> 

如果想使用@ Resource 、@ PostConstruct、@ PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor

如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。

如果想使用@Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。同样,传统的声明方式如下:

<bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

一般来说,这些注解我们还是比较常用,尤其是Antowired的注解,在自动注入的时候更是经常使用,所以如果总是需要按照传统的方式一条一条配置显得有些繁琐和没有必要,于是spring给我们提供<context:annotation-config/>的简化配置方式,自动帮你完成声明。

但是你可能也注意到了现在的注解很多,仅仅这几个注解恐怕是不够的,不怕一万就怕万一。。。。。。。。。。。。。。

比如这几个就没有:@component,@service,@Repository,@Controller

<context:component-scan />篇

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

已经能在持久化层中进行异常转换时被作为标记使用了。”

其他的先不说就单单说他的包过滤就感觉很好:

<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> 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

综上所述:一般的话还是使用<context:component-scan />吧!因为他不仅包含了<context:annotation-config/>还包含了其他的注解,特别是现在springMVC这么火的时候。。。

继续阅读