獲取springMvc中的bean
阿新 • • 發佈:2019-01-09
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>context</servlet-name> <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext-servlet.xml</param-value> <load-on-startup>1</load-on-startup> </init-param> </servlet>
web.xml配置資訊(舉例),以下是我獲取bean的方法
ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
DialManageService dialManageService = (DialManageService)context.getBean("DialManageService");
結果報以下異常
簡單說就是獲取不到這個bean,試了幾次還是這樣的錯,感覺應該是不再同一個上下文,在網上找了下,發現下面的帖子有有用資訊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)
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就獲取不到了,很有用,記錄下