当前位置: 代码迷 >> Web前端 >> 在Java Web应用中获取Spring治理的Bean的方法
  详细解决方案

在Java Web应用中获取Spring治理的Bean的方法

热度:328   发布时间:2013-10-22 16:16:51.0
在Java Web应用中获取Spring管理的Bean的方法

        前段时间在项目中遇到了这样一种问题:需要在JSP中访问后台由Spring管理的业务类代码,而这些业务类内部又涉及到了其它若干类的注入,如jdbc的service。

        首先想到的是使用WebApplicationContext,即在jsp页面中以servletContext为参数,调用WebApplicationContextUtils工具的getWebApplicationContext或getRequiredWebApplicationContext方法:

<%
         ApplicationContext ac =WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
         ReportFunctions  rf =(ReportFunctions)ac.getBean(ReportFunctions.class);
         out.print(rf.devCountTableListAllZone());
%>

        此方法需要在页面引用org.springframework.web.context.support.WebApplicationContextUtilsorg.springframework.context.ApplicationContext两个类,当多个jsp页面有同样需求的时候,这种写法显得比较繁琐,且重用性不高,于是笔者想到了使用一个工具类的静态变量来保存applicationContext,这样就可以在所有的java代码中方便地引用它了!而在Spring中,得到并保存applicationContext的最便捷的方法莫过于实现ApplicationContextAware接口了,于是有了下面的工具类:

 

        于是,我们只需要(在jsp页面)中引用SpringContextHolder,就可以轻松获取Spring管理的bean了:

ReportFunctions reportF =SpringContextHolder.getBean(ReportFunctions.class);

 

        不过话说回来,提醒大家要注意的是,虽然jsp页面可以很方便地引用后台的所有业务代码,jsp页面应该主要用于展示层,而不应该混入过多的控制层代码。

  相关解决方案