Spring集成web环境(使用封装好的工具)
接上文spring集成web环境(手动实现)
##########代码接上文#############
spring提供了一个监听器ContextLoaderListener对上述功能的封装,该监听器内部加载spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具WebApplicationContextUtils供使用者获取上下文对象
1.导入spring-web坐标
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId><version>5.2.9.RELEASE</version></dependency>
2.在web.xml中配置ContextLoaderListener监听器
<listener><listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>listener><context-param><param-name>contextConfigLocationparam-name><param-value>classpath:applicationContext.xmlparam-value>context-param>
3.使用WebApplicationContextUtils获取上下文对象ApplicationContext
public class UserServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) {ServletContext servletContext = this.getServletContext();ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(servletContext);UserService userService = app.getBean(UserService.class);userService.save1();}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);}
}
4.启动服务器,访问userServlet
结果:sava running . . .
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
