您的位置:首页 > 编程语言 > Java开发

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

2015-08-26 09:35 447 查看
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分散在不同包中,不好配置.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: