如何在java类中和jsp页面取Spring bean对象
发布网友
发布时间:2022-04-22 08:20
我来回答
共2个回答
热心网友
时间:2023-12-02 00:02
ServletContext context = req.getServletContext();
WebApplicationContext appContext =
WebApplicationContextUtils.getWebApplicationContext(context);
// 获得userService实例
userService = (UserService)context.getBean("userService");
热心网友
时间:2023-12-02 00:02
web环境中:
web.xml中配置
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>petclinic.root4</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
jsp页面中取
<%@page import="org.springframework.context.ApplicationContext" %>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils" %>
<%@page import="com.future.iaasmanager.action.DataCenterAction" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
out.println(((DataCenterAction)ctx.getBean("dataCenterAction")).getPageSize());
%>
</body>
</html>
还有第二种方法:
WebApplicationContext wac = (WebApplicationContext)
config.getServletContext().getAttribute(WebApplicationContext.
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
User u = (User) wac.getBean("user");
测试类中:
Resource res = new FileSystemResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
or
ClassPathResource res = new ClassPathResource("beans.xml");
XmlBeanFactory factory = new XmlBeanFactory(res);
or
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext(
new String[] {"applicationContext.xml", "applicationContext-part2.xml"});