spring中<context:annotation-config>和<context:component-scan>标签的区别

一、<context:annotation-config>的作用:用于开启spring中的注解,就是激活那些已经在spring容器中注册过的Bean的注解。

在没有使用<context:annotation-config>之前:

当我们需要使用BeanPostProcessor时,我们会在Spring配置文件中定义这些Bean,这样会显得比较笨拙。例如:

当我们需要使用@Autowired注解时,必须先在Spring配置文件中配置AutowiredAnnotationBeanPostProcessor的Bean:

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

当我们需要使用@Required注解时,必须先在Spring配置文件中配置RequiredAnnotationBeanPostProcessor的Bean:

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

类似地,使用@Resource、@PostConstruct、@PreDestroy等注解就必须声明 CommonAnnotationBeanPostProcessor;使用@PersistenceContext注解,就必须声明 PersistenceAnnotationBeanPostProcessor的Bean。这样就显得非常笨重,不优雅。因此Spring就为我们提供了一种非常方便的方式,就是使用<context:annotation- config/>隐式地向 Spring容器注册AutowiredAnnotationBeanPostProcessor、RequiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor以及PersistenceAnnotationBeanPostProcessor这4个BeanPostProcessor。

 

二、<context:component-scan>的作用:除了具有<context:annotation-config>的功能外,还具有在指定的包下进行扫描并注册bean的习惯。所以一般使用了该注解之后就可以把<context:annotation-config>省去。

  

  

 

posted @ 2017-12-01 16:20  zhangchaowu  阅读(198)  评论(0)    收藏  举报