在配置的Spring时,我们会遇到<context:annotation-config/>这一条配置,它的作用是向容器注册AutowiredAnnotationBeanPostProcessor(@Autowired)、CommonAnnotationBeanPostProcessor(@ Resource 、@ PostConstruct、@ PreDestroy)、PersistenceAnnotationBeanPostProcessor (@PersistenceContext)和RequiredAnnotationBeanPostProcessor (@Required)这 4 个BeanPostProcessor,而注册这4个bean的作用是为了系统能够识别相应的注解。如果你想使用@Autowired注解,那么就必须事先在Spring容器中声明AutowiredAnnotationBeanPostProcessorBean,传统声明方式为:
<bean class="org.springframework.beans.factory.annotation. AutowiredAnnotationBeanPostProcessor "/>
假如有很多注解需要使用,那么传统的声明方式是繁琐的,所以Spring给我们提供了<context:annotation-config/>的简化配置方式,自动完成声明。不过,我们使用注解的时候一般都会配置扫描包路径:<context:component-scan base-package=”XX.XX”/>,而该配置也包含了自动注册上述的功能,因此使用<context:component-scan base-package=”XX.XX”/>的时候就可以省略<context:annotation-config/>了。
Spring配置中的<context:annotation-config/>
最新推荐文章于 2024-10-02 14:23:12 发布