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分散在不同包中,不好配置.

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM