javaWeb项目有:domain->dao->service->web
在web层需要编写各种servlet,每个servlet是一个业务,需要调用各种方法、对象,因此需要总是先写:
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
StuService stu = app.getBean(StuService.class);
第一句是加载配置文件,但是不应该每次用的时候调用,而是在服务器启动时加载一次。
解决该问题的原始方法是:创建ServletContextListener监听器监听web应用的启动,启动时创建ApplicationContext,存储到servletContext域中;关闭时销毁。
spring框架提供的方法是:使用监听器ContextLoaderListener完成。该监听器内部加载spring配置文件,创建对象,并存储到ServletContext中,并提供了一个客户端工具WebApplicationContextUtils供使用者获取应用上下文对象。
使用:
-
导入spring-web坐标
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>5.0.2.RELEASE</version> </dependency>
-
在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
<!-- 全局初始化参数--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- 监听器--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
-
在servlet/业务方法中使用WebApplicationContextUtils获取应用上下文对象ApplicationContext
ServletContext servletContext = this.getServletContext(); WebApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext); StuService stu = app.getBean(StuService.class); stu.save();