您的位置:首页 > 编程语言 > Java开发

在JSP页面中调用Spring容器注入的Bean的2种方法

2017-07-25 10:34 701 查看
方法一:

1.首先在jsp中导入:

 

<jsp:directive.page import="org.springframework.web.context.WebApplicationContext"/>

 

2.然后可以调用spring容器管理的Bean了(这里实例调用的是CalendarMapper 对象):

Jsp中调用spring管理的Bean代码如下:
WebApplicationContext context = (WebApplicationContext)this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);  

CalendarMapper calendarMapper = (CalendarMapper)context.getBean("calendarMapper");

方法二:

1.在jsp中导入:
 
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
 
<%@page import="org.springframework.web.context.WebApplicationContext" %>
 
2.然后可以调用spring容器管理的Bean了:
 
WebApplicationContext context=WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());

CalendarMapper calendarMapper = (CalendarMapper)context.getBean("calendarMapper");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: