天天看點

JSP擷取spring 的容器ApplicationContext

方式一:通過上下文

JSP擷取spring 的容器ApplicationContext

<?xml version="1.0" encoding="utf-8" ?>  

<%@ page language="java" contenttype="text/html; charset=utf-8"  

    pageencoding="utf-8"%>  

<%@page import="org.springframework.web.context.support.webapplicationcontextutils"%>  

<%@page import="org.springframework.context.applicationcontext"%>  

<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">  

<html xmlns="http://www.w3.org/1999/xhtml">  

<head>  

<meta http-equiv="content-type" content="text/html; charset=utf-8" />  

<title>insert title here</title>  

</head>  

<body>  

<%  

servletcontext context = request.getsession().getservletcontext();  

applicationcontext ctx = webapplicationcontextutils.getwebapplicationcontext(context);  

object <span style="font-size: 1em; line-height: 1.5;">supermarketdao</span><span style="font-size: 1em; line-height: 1.5;">= ctx.getbean("supermarketdao");</span>  

system.out.println("jsp:"+<span style="font-size: 1em; line-height: 1.5;">supermarketdao</span><span style="font-size: 1em; line-height: 1.5;">);</span>  

%>  

</body>  

</html>  

 問題:jsp頁面中擷取的bean與spring 容器中的bean是同一個嗎?

是的。

方式二:通過類路徑加載bean檔案,得到bean工廠

JSP擷取spring 的容器ApplicationContext

<%@page import="org.springframework.beans.factory.beanfactory"%>  

<%@page import="org.springframework.context.support.classpathxmlapplicationcontext"%>  

classpathxmlapplicationcontext appcontext = new classpathxmlapplicationcontext("beans.xml","user_beans.xml","goods_beans.xml","supermarket_beans.xml","aop.xml","upload_beans.xml");   

beanfactory factory = (beanfactory) appcontext;   

object obj=factory.getbean("supermarketdao");  

system.out.println("jsp2:"+obj);  

  問題:jsp頁面中擷取的bean與spring 容器中的bean是同一個嗎?

不是的。

總結:(1)通過webapplicationcontextutils 擷取bean是直接從spring容器中拿的;

(2)通過classpathxmlapplicationcontext,實際上又解析了一遍xml,即又建立了一個新的spring容器,所有擷取的bean與web上下文中是不同的。