博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java综合(三)springmvc与spring上下文关系
阅读量:3528 次
发布时间:2019-05-20

本文共 1713 字,大约阅读时间需要 5 分钟。

springmvc上下文继承于spring,也就是springmvc的上下文可访问spring上下文,在springmvc的上下文中可取得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分散在不同包中,不好配置.

转载地址:http://ejihj.baihongyu.com/

你可能感兴趣的文章
小甲鱼Python第三讲(小插曲之变量和字符串)
查看>>
小甲鱼Python第十一讲(一个打了激素的数组2)
查看>>
小甲鱼Python第十三讲(戴上了枷锁的列表)
查看>>
小甲鱼Python第十四讲(各种奇葩的内置方法)
查看>>
小甲鱼Python第十五讲(格式化)
查看>>
小甲鱼Python第十七讲(Python的乐高积木)
查看>>
小甲鱼Python第十八讲(函数:灵活即强大)
查看>>
小甲鱼Python第十九讲(函数,我的地盘听我的)
查看>>
小甲鱼python第二十讲(内嵌函数和闭包)
查看>>
小甲鱼Python第二十一讲(lambda表达式)
查看>>
小甲鱼Python第二十二讲(递归)
查看>>
小甲鱼Python第二十三讲、第二十四讲(递归-这帮小兔崽子、汉诺塔)
查看>>
小甲鱼Python第二十五讲、第二十六讲(字典)
查看>>
小甲鱼Python第二十七讲(集合)
查看>>
2020光学期刊一区二区影响因子发布(科睿唯安)
查看>>
可调谐半导体激光器的窄线宽测试及压缩
查看>>
matlab中 %d,%f,%c,%s
查看>>
常见的光纤接头汇总
查看>>
半导体激光器—问题整理(二)
查看>>
科研日记7.31
查看>>