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

获取springMvc中的bean

2016-07-08 14:21 337 查看
<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");


结果报以下异常

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就获取不到了,很有用,记录下
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息