在servlet容器啓動時獲取ApplicationContext上下文環境

在servlet容器啓動時獲取ApplicationContext上下文環境
public class InitListener implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
		//  容器銷燬時
		
	}

	@Override
	public void contextInitialized(ServletContextEvent sc) {
                 //容器初始化時
		//獲取applicationcontext 上下文環境
		ApplicationContext con = WebApplicationContextUtils.getWebApplicationContext(sc.getServletContext());
		IPrivilegeService service = (IPrivilegeService) con.getBean("privilegeServiceImpl");
		List<Privilege> topPrivilegeList = service.findTopList();
		sc.getServletContext().setAttribute("topPrivilegeList", topPrivilegeList);
		System.out.println("------>初始化權限列表<------");
	}

	 

}

其中在web.xml中配置一下監聽器即可。請注意保持順序

<pre name="code" class="java">	<!-- 配置Spring的用於初始化容器對象的監聽器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext*.xml</param-value>
	</context-param>

	<!--
		用於做初始化工作的監聽器,一定要配置到Spring的ContextLoaderListener之後,因爲要用到Spring的容器對象
	-->
	<listener>
		<listener-class>cn.itcast.oa.util.InitListener</listener-class>
	</listener>





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章