zoukankan      html  css  js  c++  java
  • java综合(三)springmvc与spring上下文关系

    springmvc上下文继承于spring,也就是springmvc的上下文可访问spring上下文,在springmvc的上下文中可取得spring bean.
    测试一下吧.

    1. package com.skymr.smvcs.hello.ctrl;  
    2.   
    3.   
    4. import javax.annotation.Resource;  
    5. import javax.servlet.http.HttpServletRequest;  
    6.   
    7.   
    8. import org.springframework.stereotype.Controller;  
    9. import org.springframework.web.bind.annotation.RequestMapping;  
    10. import org.springframework.web.context.WebApplicationContext;  
    11. import org.springframework.web.context.support.WebApplicationContextUtils;  
    12. import org.springframework.web.servlet.support.RequestContextUtils;  
    13.   
    14.   
    15. import com.skymr.smvcs.hello.service.HelloWorldService;  
    16. @Controller  
    17. @RequestMapping("/hello")  
    18. public class HelloWorldController{  
    19.   
    20.   
    21.     //spring注解注入  
    22.     //测试时不用注入方式  
    23. //  @Resource  
    24. //  private HelloWorldService helloWorldService;  
    25.       
    26.     @RequestMapping("/helloWorld")  
    27.     public String toHelloWorld(HttpServletRequest request){  
    28.         System.out.println("执行HelloWorldController toHelloWorld方法");  
    29.           
    30.         //取得spring 上下文  
    31.         WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());  
    32.           
    33.         //取得springmvc上下文  
    34.         WebApplicationContext mvcContext = RequestContextUtils.getWebApplicationContext(request);  
    35.           
    36.         //取得spring容器中的bean,不是用的注入方式  
    37.         //在一定的场合下,不能使用注入方式,就可以用这种方法取得bean  
    38. //      HelloWorldService helloWorldService = (HelloWorldService)springContext.getBean("helloWorldService");  
    39.         //经测试这两个上下文都能取得bean  
    40.         HelloWorldService helloWorldService = (HelloWorldService)mvcContext.getBean("helloWorldService");  
    41.         helloWorldService.say();  
    42.         return "index";  
    43.     }  
    44.       
    45. }  





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

  • 相关阅读:
    mod_rewrite
    敏捷开发
    转python和ruby的相同点
    ESB总线知识小结
    使用 squid 2.7 for windows 进行无缓存反向代理
    初探K2workflow
    没激情的工作
    多易拍 二次开发
    查看数二进制代码片段
    生成随机数
  • 原文地址:https://www.cnblogs.com/bkyliufeng/p/6293681.html
Copyright © 2011-2022 走看看