Spring MVC 在JSP中獲取service層的Bean對象

在使用spring框架的過程當中,受益於Spring框架中Bean的自動注入的方便,同時在JSP中須要使用到service層中的對象的時候,由於在service層都有dao層的自動注入,因此如果在JSP中直接使用如:java

 

[java] view plain copyweb

 print?spring

  1. ServiceUser su = new ServiceUser();  

會出現空指針的狀況,這種空指針是因爲在ServiceUser中使用到了DaoUser的自動注入,也就是說,直接在JSP頁面中實例化一個ServiceUser對象,其中的DaoUser是沒有被注入的。爲了解決這種情況,想到Spring這個容器在Web程序運行起來後,其中的全部對象都已經被裝入到了ApplicationContext對象(即Spring容器)中,能不能直接從容器中把serviceUser這個Bean取出來呢?答案是確定的,以下:數據庫

 

 

[java] view plain copyapp

 print?框架

  1. <%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>  
  2. <%@page import="org.springframework.context.ApplicationContext"%>  
  3.   
  4. /** 從Spring容器中獲取 ServiceUser這個Bean對象 */  
  5.     ServletContext sc = this.getServletContext();  
  6.     ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);  
  7.     ServiceUser serviceuser = (ServiceUser) ac.getBean("serviceUser");// 這裏就能夠直接取出所須要的service層中的Bean了  


這樣,在後面使用serviceuser這個對象再對數據庫進行訪問就不會再報空指針異常了。this

相關文章
相關標籤/搜索