java综合(三)springmvc与spring上下文关系


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


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值