java综合(三)springmvc与spring上下文关系
2015-08-26 09:35
447 查看
springmvc上下文继承于spring,也就是springmvc的上下文可访问spring上下文,在springmvc的上下文中可取得spring bean.
测试一下吧.
spring配置小技巧:import标签
<import resource="classpath*:config/spring/spring_annotation-import.xml"/>
在团队开发时候,每个人都常去改动spring配置文件,不科学,使用这个技巧方便,每个都有各自的配置文件了.
项目较大,有较多的bean时,可以将其分散到子文件中.
虽然spring还有自动扫描的功能,但我感觉也不怎么好,需要去扫描,影响性能;而且各个Bean分散在不同包中,不好配置.
测试一下吧.
package com.skymr.smvcs.hello.ctrl; 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; import com.skymr.smvcs.hello.service.HelloWorldService; @Controller @RequestMapping("/hello") public class HelloWorldController{ //spring注解注入 //测试时不用注入方式 // @Resource // private HelloWorldService helloWorldService; @RequestMapping("/helloWorld") public String toHelloWorld(HttpServletRequest request){ System.out.println("执行HelloWorldController toHelloWorld方法"); //取得spring 上下文 WebApplicationContext springContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext()); //取得springmvc上下文 WebApplicationContext mvcContext = RequestContextUtils.getWebApplicationContext(request); //取得spring容器中的bean,不是用的注入方式 //在一定的场合下,不能使用注入方式,就可以用这种方法取得bean // HelloWorldService helloWorldService = (HelloWorldService)springContext.getBean("helloWorldService"); //经测试这两个上下文都能取得bean HelloWorldService helloWorldService = (HelloWorldService)mvcContext.getBean("helloWorldService"); helloWorldService.say(); return "index"; } }
spring配置小技巧:import标签
<import resource="classpath*:config/spring/spring_annotation-import.xml"/>
在团队开发时候,每个人都常去改动spring配置文件,不科学,使用这个技巧方便,每个都有各自的配置文件了.
项目较大,有较多的bean时,可以将其分散到子文件中.
虽然spring还有自动扫描的功能,但我感觉也不怎么好,需要去扫描,影响性能;而且各个Bean分散在不同包中,不好配置.
相关文章推荐
- jxl(Java Excel API) 使用方法 【2】
- jxl(Java Excel API) 使用方法 【1】
- java excel Workbook API
- 使用JAVA发多人邮件,有附件,有完整代码,复制便可用
- spring的annotation-driven配置事务管理器详解
- MyEclipse 控制台等显示在底部
- Java中的反射机制
- Spring的事务配置
- eclipse导入hadoop源码错误处理
- MyEclipse 中各种 libraries 的含义
- java多线程(六)深入理解volitale关键字
- java多线程(五)synchronized关键字修饰代码块
- 关于Java的Map/List
- Spring MVC程序中得到静态资源文件css,js,图片
- Java IO流
- 简单且线程安全的两个单例模式java程序
- Project facet Java version 1.7 is not supported
- eclipse时间,log时间,控制台打印时间
- java之异常处理
- 从零开始学Java之五种内部类将线程隐藏类中