zoukankan      html  css  js  c++  java
  • 15.SpringMVC和Spring上下文关系(为什么SpringMVC可以调用到Spring)

    springmvc上下文继承于spring,

    也就是springmvc的上下文可访问spring上下文,在springmvc的上下文中可取得spring bean.

    spring上下文是spring启动的时候加载的spring的配置文件,目前用到的只是Spring bean 的上下文文件,

    每一个dispatcherServlet上下文去对应一个spring上下文

    SpringMVC只要写一个注解就可以拿到上下文,而不用去配置容器

    测试一下两个的关系 

    1.SpringController

    package com.tgb.web.controller.annotation;
    
    import javax.annotation.Resource;
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.context.WebApplicationContext;
    import org.springframework.web.context.support.WebApplicationContextUtils;
    import org.springframework.web.servlet.support.RequestContextUtils;
    
    @Controller
    public class SpringController {
    
        /*@Resource(name="springManager")
        private ISpring springManager;*/
        
        @RequestMapping("/spring/get")
        public String get(HttpServletRequest request){
            //spring的上下文
            WebApplicationContext ac1 = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
            //springMVC的上下文
            WebApplicationContext ac2 = RequestContextUtils.getWebApplicationContext(request);
            
            //ISpring springManager = (ISpring) ac1.getBean("springManager");
            ISpring springManager = (ISpring)ac2.getBean("springManager");
            
            System.out.println(springManager.get());
            return "/success";
        }
    }

    2.防止每个人在开发的时候,都对一个spring.xml进行修改,则要写很多bean且会混乱

    spring配置小技巧:import标签

    团队开发时,各自维护自己的spring.xml 配置文件,这时就可以使用一个公用的spring.xml来进行导入就可以了。

    <import  resource="classpath*:com/xdy/controller/annotation/springAnnotation-import.xml" /> 

    spring配置小技巧:import标签
    <import resource="classpath*:config/spring/spring_annotation-import.xml"/>
    在团队开发时候,每个人都常去改动spring配置文件,不科学,使用这个技巧方便,在开发的时候,最好每个都有各自的配置文件了,每个人用一个配置文件,减少冲突
    项目较大,有较多的bean时,可以将其分散到子文件中.
    虽然spring还有自动扫描的功能,但我感觉也不怎么好,需要去扫描,影响性能;而且各个Bean分散在不同包中,不好配置.

  • 相关阅读:
    试述软件的概念和特点?软件复用的含义?构件包括哪些?
    Spring Security基本用法
    java中跳出循环的方式
    cookie和session区别
    spring中类型注解下的bean的加载顺序
    常见的异常
    aop使用场景
    缓存类似于redis
    旧版redis使用
    获取rdis的几种方式
  • 原文地址:https://www.cnblogs.com/chenxiaomeng/p/5800251.html
Copyright © 2011-2022 走看看