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

[size=medium]本文将这样展开:
[color=red]1.[/color] 简单讲解Spring中的<context:component-scan /> <context:annotation-config />
<mvc:annotation-driven /> 这三者的作用
[color=red]2. [/color]讲解下我们经常看到的在web.xml文件中定义的ContextLoaderListener和DispatcherServlet的区别

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

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

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

[color=blue] 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.[/color]

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值