获取springMvc中的bean


    org.springframework.web.context.ContextLoaderListener


    context
    org.springframework.web.context.ContextLoaderServlet
    1
 

SpringMVC
org.springframework.web.servlet.DispatcherServlet
  
        contextConfigLocation  
        classpath:spring/applicationContext-servlet.xml
        1
    

web.xml配置信息(举例),以下是我获取bean的方法

ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
		DialManageService dialManageService = (DialManageService)context.getBean("DialManageService");

结果报以下异常


2016-07-08 14:07:12,328 ERROR [http-bio-8080-exec-5] ManageToolsController - --dialTest error --
org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'DialManageService' is defined
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:698)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1174)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:283)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1045)
	
简单说就是获取不到这个bean,试了几次还是这样的错,感觉应该是不再同一个上下文,在网上找了下,发现下面的帖子有有用信息

http://bbs.csdn.net/topics/390977647

原来springMvc和spring上下文不是同一个,spring是用listener初始化的上下文,称为root上下文,springMvc是通过servlet初始化的上下文,称为servlet上下文,servlet里的能获取root里的,反之就获取不到,servlet应该是root的子上下文,而我获取bean的地方是处于root上下文的,怎么才能通过代码获取servlet的上下文呢?帖子里给我满意的答案,于是我修改代码如下

			ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext(),
"org.springframework.web.servlet.FrameworkServlet.CONTEXT.SpringMVC");
			DialManageService dialManageService = (DialManageService)context.getBean("DialManageService");

WebApplicationContextUtils.getWebApplicationContext()方法的第二个参数,其中SpringMVC是servlet上下文配置的servlet名字,这样获取到的上下文就是servlet上下文,这样就能成功获取到这个bean,如果现在用这个context获取root上下文的bean就获取不到了,很有用,记录下

你可能感兴趣的:(学习笔记,springMvc,获取bean)