Spring中的<context:annotation-config/>

来源:互联网 发布:神优化游戏 编辑:程序博客网 时间:2024/06/18 04:06

在配置Spring的配置文件中,会常见到< context:annotation-config/>,其实它的作用是向Spring容器中注册四个BeanPostProcessor,其四个分别为:

  • AutowiredAnnotationBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotationBeanPostProcessor
  • RequireAnnotationBeanPostProcessor

注册这四个的作用,就是为了让系统能够识别相应的注解

例如:
先使用@Autowired注解,就必须声明AutowiredAnnotationBeanPostProcessor的Bean,传统的声明方式为:
<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/>

若想使用@Resource、@PostConstruct、@PreDestroy等就必须声明CommonAnnotationBeanPostProcessor的Bean。

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

若想使用@Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

这样用起来会很麻烦,所以spring给我们提供了<context:annotation-config/>的简化配置方式,将自动完成声明。

在使用注解时,一般会配置扫描包路径选项:<context:component-scan basc-package="包名"/>,该配置包含了自动注入上述processor的功能,因此当使用<context:component-scan/>时,就可以将<context:annotation-config/>移除。

0 0