Spring工具类:WebApplicationContextUtils
2016-05-16 16:03
134 查看
当 Web 应用集成 Spring 容器后,代表 Spring 容器的WebApplicationContext对象将以
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在ServletContext的属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:
但通过位于 org.springframework.web.context.support 包中的WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。
servletContext sc 换成
1.servlet.getServletContext()
2.this.getServletContext()
3.request.getSession().getServletContext();
实例:
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在ServletContext的属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:
WebApplicationContext wac = (WebApplicationContext)servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
但通过位于 org.springframework.web.context.support 包中的WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:
ApplicationContext ac1 =WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); ApplicationContext ac2 =WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ac1.getBean("beanId"); ac2.getBean("beanId");
说明:
这种方式适合于采用Spring框架的B/S系统,通过ServletContext对象获取ApplicationContext对象,然后在通过它获取需要的类实例。
上面两个工具方式的区别是,前者在获取失败时抛出异常,后者返回null。
servletContext sc 换成
1.servlet.getServletContext()
2.this.getServletContext()
3.request.getSession().getServletContext();
实例:
public class demoServlet extends HttpServlet { IDemoWS demoWS; public void init() throws ServletException { super.init(); ServletContext servletContext = this.getServletContext(); WebApplicationContext ctx =WebApplicationContextUtils.getWebApplicationContext(servletContext); demoWS = (ISignpicWS)ctx.getBean("demoWS"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { .....//request.getSession().getServletContext() } }
相关文章推荐
- 扯谈spring mvc之WebApplicationContext的继承关系
- java spring代码通用结构-webapp
- webAPP和原生Android的APP有什
- maven webapp后无法添加src/main/java和src/main/test
- Cordova webapp实战开发:(7)如何通过简单的方法做到,不重新发布APP来修复bug、增加功能、或者躲开苹果的一些严格审核?
- Cordova webapp实战开发:(5)如何写一个Andorid下自动更新的插件?
- Maven学习之17使用jetty来发布webapps(成功)
- 我们为什么要用Ionic开发webApp
- spring java 获取webapp下文件路径
- Maven学习之15使用jetty来发布webapps(失败)
- tamcat学习2之使用Maven新建webapp,并从HelloServlet中读取变量值
- tamcat学习1之使用Maven新建webapp
- WebAPP与原生APP的交互设计区别
- webapp之设计尺寸转编码所设尺寸
- springmvc 加载WebApplicationContext源码分析
- 手工MAVEN建立WEBAPP项目并打包部署
- angularjs+ionic高大上的webApp(环境配置篇)
- webapp思路和rem适配极其viewport
- phonegap------angularjs+ionic高大上的webApp
- Eclipse建立webapp3.0以上的Maven项目