Spring中<context:annotation-config/>的作用

 1.context:annotation-config   开启基于注解支持

<context:annotation-config/>的作用是为了你的系统能够识别相对应的注解。可以自动隐式地向Spring容器注册以下四个BeanPostProcessor:

  • AutowiredAnnotationBeanPostProcessor
  • CommonAnnotationBeanPostProcessor
  • PersistenceAnnotationBeanPostProcessor
  • RequiredAnnotationBeanPostProcessor

2.传统的声明方式注入到IOC容器中

<bean class="com.mhys.bean.Book" id="book" scope="singleton"/>

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

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

3.如果想使用@Autowired注解,那么就必须事先在 Spring 容器中声明 AutowiredAnnotationBeanPostProcessor Bean。

4.如果想使用 @Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

以上这些注解是很常用的,如果按照传统的方式进行配置将会非常繁琐,所以Spring给我们提供了一个简便的方式:<context:annotation-config/>,使用该元素可以自动声明以上注解。

注:由于<context:component-scan base-package=”xx.xx”/>也包含了自动注入上述Bean的功能,所以<context:annotation-config/> 可以省略。如果两者都进行了配置,则只有前者有效。

3.context:component-scan   自动组件扫描

<context:component-scan base-package="com.mhys"/>

Spring给我们提供了context:annotation-config 的简化的配置方式,自动帮助你完成声明,并且还自动搜索@Component , @Controller , @Service , @Repository等标注的类。

context:component-scan除了具有context:annotation-config的功能之外,context:component-scan还可以在指定的package下扫描以及注册javabean 。还具有自动将带有@component,@service,@Repository等注解的对象注册到spring容器中的功能。

因此当使用 context:component-scan 后,就可以将 context:annotation-config移除。

原文地址:https://www.cnblogs.com/tangxinwang/p/14463619.html