Spring IoC之

<context:annotation-config/>

在基于主机方式配置Spring时,Spring配置文件applicationContext.xml,你可能会见<context:annotation-config/>这样一条配置,它的做用是隐式的向Spring容器注册spring

  • AutowiredAnnotationBeanPostProcessorapp

  • CommonAnnotationBeanPostProcessorui

  • PersistenceAnnotationBeanPostProcessorspa

  • RequiredAnnotationBeanPostProcessor code

这4个BeanPostProcessor.注册这4个bean处理器主要的做用是为了你的系统可以识别相应的注解。   component

例如:xml

     若是想使用@Autowired注解,须要在Spring容器中声明AutowiredAnnotationBeanPostProcessor Bean。传统的声明方式以下:                 递归

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

    若是想使用@PersistenceContext注解,须要在Spring容器中声明PersistenceAnnotationBeanPostProcessor Bean。 传统的声明以下:               it

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

   若是想使用@Required注解,须要在Spring容器中声明RequiredAnnotationBeanPostProcessor Bean。传统声明方式以下:             io

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

    若是想使用@Resource、@ PostConstruct、@ PreDestroy等注解就要声明CommonAnnotationBeanPostProcessor。 传统申明方式以下:

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

       因此,若是按照传统声明一条一条去声明注解Bean,就会显得十分繁琐。所以若是在Spring的配置文件中事先加上<context:annotation-config/>这样一条配置的话,那么全部注解的传统声明就能够被  忽略,即不用在写传统的声明,Spring会自动完成声明。

<context:component-scan/> 

      <context:component-scan/>的做用是让Bean定义注解工做起来,也就是上述传统声明方式。 它的base-package属性指定了须要扫描的类包,类包及其递归子包中全部的类都会被处理。

        值得注意的是<context:component-scan/>不但启用了对类包进行扫描以实施注释驱动 Bean 定义的功能,同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了 AutowiredAnnotationBeanPostProcessor 和  CommonAnnotationBeanPostProcessor),所以当使用  <context:component-scan/> 后,就能够将 <context:annotation-config/> 移除了(若是不使用PersistenceContext和Required注解的话)。

相关文章
相关标签/搜索