<context:annotation-config/>,<context:component-scan>,<mvc:annotation-driven/>,<tx:annotation-driven/>简单说明

1.<context:annotation-config/>

 》可能大家没见过这个标签,但是它提供的注解的使用你一定用过,比如@Autowired,@Resource,@PostConstruct等,至于你为什么没用到这个标签,还能正常使用且由效果呢,请继续往下看

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

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

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

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

  使用<context:annotation-config/>隐式地向 Spring容器注册这4个BeanPostProcessor:

    * AutowiredAnnotationBeanPostProcessor、
    * RequiredAnnotationBeanPostProcessor、
    * CommonAnnotationBeanPostProcessor、
    * PersistenceAnnotationBeanPostProcessor

  》我们通过上面的注解向对象的属性注入Bean,前提这个Bean得存在于spring的容器中,不管是xml或注解的方式注册在spring,注入属性前必须bean存在spring IOC中,否则不起作用


2.<context:component-scan>
  》<context:component-scan>做了<context:annotation-config>要做的事情,还额外支持@Component,@Repository,@Service,@Controller注解,所以配置了<context:component-scan>就不需要在配置<context:annotation-config/>

  》但有时你即没有配置<context:component-scan>,也没有配置<context:annotation-config/>,@Autowired等标签的使用照样有效果,确实被注入进去了;其实在启动spring IoC时,容器自动装载了一个AutowiredAnnotationBeanPostProcessor后置处理器,当容器扫描到@Autowied、@Resource或@Inject时,就会在IoC容器自动查找需要的bean,并装配给该对象的属性

小结:<context:component-scan>扫描指定包,标有特定的注解的类会被注册到spring ioc中,以及能将类中标有特定注解的属性对象进行注入。

3.<mvc:annotation-driven/>
  》看前缀就应该知道是springmvc所需要的注解。<mvc:annotation-driven/>相当于注册了DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter两个bean,配置一些messageconverter。即解决了@Controller注解的使用前提配置。

    》我们找到对应的实现类是:

    org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser。

    通过阅读类注释文档,我们发现这个类主要是用来向工厂中注册了

      RequestMappingHandlerMapping

      BeanNameUrlHandlerMapping

      RequestMappingHandlerAdapter

      HttpRequestHandlerAdapter

      SimpleControllerHandlerAdapter

      ExceptionHandlerExceptionResolver

      ResponseStatusExceptionResolver

      DefaultHandlerExceptionResolver

    上面几个Bean实例。这几个类都是用来做什么的呢?

      前两个是HandlerMapping接口的实现类,用来处理请求映射的。

      其中第一个是处理@RequestMapping注解的。

      第二个会将controller类的名字映射为请求url。

      中间三个是用来处理请求的。具体点说就是确定调用哪个controller的哪个方法来处理当前请求。

      第一个处理@Controller注解的处理器,支持自定义方法参数和返回值(很酷)。

      第二个是处理继承HttpRequestHandler的处理器。

      第三个处理继承自Controller接口的处理器。

      后面三个是用来处理异常的解析器。

    另外还将提供以下支持:

      ① 支持使用ConversionService实例对表单参数进行类型转换; 
      ② 支持使用@NumberFormatannotation、@DateTimeFormat注解完成数据类型的格式化; 
      ③ 支持使用@Valid注解对Java bean实例进行JSR 303验证; 
      ④ 支持使用@RequestBody和@ResponseBody注解

4.<tx:annotation-driven/>

  》看前缀知道是提供给事务控制的注解驱动,它支持@Transactional等的支持,也是在spring容器注册了事务支持的bean

 

文章参考自:https://www.cnblogs.com/DarrenChan/p/6892655.html

posted @ 2020-05-29 17:19  爱编程DE文兄  阅读(292)  评论(0编辑  收藏  举报