Spring+SpringMVC 中获取javabean
网上获取的方式比较多,但总是比较模糊。时而有用时而没用,关键是配置杂乱,记录不全。
而Spring的容器和SpringMVC的容器又是父子关系,相互之间并不是相同的,我这里介绍一种比较靠谱的获取方式,可以分别获取父容器和子容器。
第一步 web.xml中配置监听
<!-- spring容器监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
第二步 任意类中获取
this.rootWac = ContextLoader.getCurrentWebApplicationContext();
this.servletContext = rootWac.getServletContext();
this.mvcApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext, "org.springframework.web.servlet.FrameworkServlet.CONTEXT.mvc-dispatcher");
this.viewResolver = this.mvcApplicationContext.getBean(FreeMarkerViewResolver.class);
尊重作者,转载请注明出处!
版权申明:本文版权归作者所有,未经授权,任何单位或个人不得以任何形式转载、摘编或利用其它方式使用本博客内容。作者保留追究相关法律责任的权利。如需使用博客内容,请与作者联系获得授权。感谢对本文的尊重与支持。
免责声明:本网站所载内容仅供参考,不构成任何专业建议。用户基于本网站内容作出的决策,风险自担。对于因使用本网站内容而产生的任何直接或间接损失,本网站不承担任何责任。请用户审慎判断,理性使用。