在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>


 


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐