http://hw1287789687.iteye.com/blog/1943433
Jsp 中如何获取spring的bean呢?
方式一:通过上下文
<?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工厂
<?xml version="1.0" encoding="UTF-8" ?>
<%@page import="org.springframework.beans.factory.BeanFactory"%>
<%@page import="org.springframework.context.support.ClassPathXmlApplicationContext"%>
<%@ 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>
<%
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);
%>
</body>
</html>
问题:JSP页面中获取的bean与spring 容器中的bean是同一个吗?
不是的。
总结:(1)通过WebApplicationContextUtils 获取bean是直接从spring容器中拿的;
(2)通过ClassPathXmlApplicationContext,实际上又解析了一遍xml,即又创建了一个新的spring容器,所有获取的bean与web上下文中是不同的。