WebApplicationContextUtils 可以获取
1
2
|
WebApplicationContext WebApplicationContext 可以获取bean,然后执行方法获取数据。 |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
package cn.sccl.common.web;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.WebApplicationContextUtils;
import cn.sccl.common.service.BizCodeManager;
import cn.sccl.common.web.util.Log4jWebConfigurer;
import cn.sccl.pms.model.Division;
import cn.sccl.pms.model.DivisionQuery;
import cn.sccl.pms.service.DivisionManager;
public class StartupListener extends ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
super .contextInitialized(event);
ServletContext context = event.getServletContext(); //获取servletContext
//也可以在实现了HttpServlet接口中获取,ServletContext servletContext = this.getServletContext();
setupContext(context);
}
protected void setupContext( final ServletContext context) {
// WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); //推荐使用这种,因为getRequiredWebApplicationContext要求servletContext中必须要有ApplicationContext
ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
// 行政区划
DivisionManager divisionManager = (DivisionManager) ctx.getBean( "divisionManager" ); //得到manager
List<Division> divisions = divisionManager.query( new DivisionQuery());
//将数据放入ServletContext 页面中就在application中获取,因为application和servletContext对应
context.setAttribute( "divisions" , divisions);
}
}
|
本文转自建波李 51CTO博客,原文链接:http://blog.51cto.com/jianboli/1890712,如需转载请自行联系原作者