分享

Spring 一些标签的作用,ContextLoaderListener和DispatcherServlet两者的配置文件的区别

 IT民工收藏 2014-07-29
本文将这样展开:
1. 简单讲解Spring中的<context:component-scan /> <context:annotation-config /> 
<mvc:annotation-driven /> 这三者的作用
2. 讲解下我们经常看到的在web.xml文件中定义的ContextLoaderListener和DispatcherServlet的区别

<context:annotation-config />
这个标签告诉Spring到bean类中寻找一些annotation定义的类,
这些annotation基本如下:
@Autowired  @PostConstruct  @PreDestroy  @Resource 等。
需要注意的是。这个标签并没有激活@Transactional 和 @TransactionAttribute

<context:component-scan base-package=""/>
这个标签用于告诉Spring搜索我们指定的包下面以及一些需要被自动注入的bean。
默认支持的annotation:@Component @Repository  @Service @Controller
需要注意的是:这个标签页实现了和annotation-config同样的效果。

<mvc:annotation-driven />
刚开始的时候我也很困惑为什么需要配置这个标签,但是当我们在配置SpringMVC的控制器的时候,我们发现有RequestMapping的存在,这个标签的作用之一就是告诉Spring去检测RequestMapping。其他的作用如下:
- 激活@ExceptionHandler这个annotation
- 配置了这个标签还可以将RequestMappingHandlerAdapter注册到Spring中
- 是SpringMVC提供默认的类型转化,因为我们没有在<mvc:annotation-driven/> 的属性中配置ConversionService
- 当然,这个标签还起到了一些其他的作用,我不怎么会翻译,怕变味。下面是英文原文:

It also enables the following:
1. Spring 3 style type conversion through a ConversionService instance in addition to the JavaBean PropertyEditors used for Data Binding.
2. Support for formatting Number fields using the @NumberFormat annotation through the ConversionService
3. Support for formatting Data,Calendar,Long and Joda Time fields using the @DateTimeFormat annotation, if Joda Time 1.3 or higher is present on the classpath.
4. Support for validating @Controller inputs with @Valid if a JSR-303 Provider is present on the classpath.
5. HttpMessageConverter support for @RequestBody method parameters and @ResponseBody method return values form @RequestMapping or @ExceptionHandler methods.


2.  下面是讲解web.xml配置是ContextLoaderListener和DispatcherServlet的区别:
- ContextLoaderListener是在我们的web容器启动的时候启动的,默认会加载/WEB-INF/下面的applicationContext.xml文件。并创建一个WebApplicationContext容器。
- DispatcherServlet是在我们第一次访问我们的应用的时候创建的。这时候它默认会将配置在/WEB-INF下面的<servlet-name>-servlet.xml配置文件,然后也创建一个WebApplicationContext。这个WebApplicationContext将之前ContextLoaderListener创建的容器作为父容器,因此在父容器中配置的所有Bean都能够被注入到子容器中。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多