springMVC容器和Spring容器

一、两个容器创建的时机
1.Spring容器
创建于ContextLoaderListener,当该监听器监听到项目启动时,便会创建applicationContext,并将此对象放入servletCongtext中。

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml,classpath:spring-mybatis.xml</param-value>
</context-param>
<listener>
    <description>spring监听器</description>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

2.SpringMvc容器
该容器创建于DispatchServlet初始化时。

 <servlet>
        <description>spring rest</description>
        <servlet-name>rest</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

由于listener的执行顺序优先于servlet所以Spring容器先于SpringMvc容器存在,即Spring容器为父容器,SpringMvc容器为子容器。因父容器初始化时会将自己放入servletContext中,

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

子容器在初始化时就能得到父容器的存在,因而也就能使用父容器中的bean。

结语:使用spring容器的目的,我认为就是为了区分哪些bean是可以脱离web环境使用的。

问题一、为什么Controller注册在父容器中,注册在子容器中时,springMVC无法处理请求呢?
答:RequestMappingHandleMapping在找controller时,默认是不会从父容器中找的。所以我们可以手动的配置它从父容器找。但是这样针对特定的HandlerMapping配置不好。可以配置controller使用子容器装载。这样既分工明确,又可以免于配置。

注:采用父子容器制对事务的影响,子容器中即springMvc.xml中必须配置

<!-- 注解方式配置事物 -->
    <tx:annotation-driven  proxy-target-class="true" transaction-manager="transactionManager" />

否则事务无法生效。原因待查。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值