WebApplicationContextUtils 可以获取
WebApplicationContext WebApplicationContext 可以获取bean,然后执行方法获取数据。
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); } }
时间: 2024-11-05 09:21:36