一、项目结构及相应jar包,如下图
二、UserService代码
package com.hjp.service;/** * Created by JiaPeng on 2015/11/15. */public class UserService { public void addUser() { System.out.println("add user"); }}
三、创建一个HelloServlet,代码:
package com.hjp.web.servlet;import com.hjp.service.UserService;import org.springframework.web.context.WebApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;import java.io.IOException;/** * Created by JiaPeng on 2015/11/15. */public class HelloServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { this.doGet(request, response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { //方式1,手动从ServletContext作用域中获得内容 //WebApplicationContext applicationContext = (WebApplicationContext) this.getServletContext().getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); WebApplicationContext applicationContext= WebApplicationContextUtils.getWebApplicationContext(this.getServletContext()); UserService userService = (UserService) applicationContext.getBean("userService"); userService.addUser(); }}
四、web.xml中配置,主要是注意监听的配置
contextConfigLocation classpath:applicationContext.xml org.springframework.web.context.ContextLoaderListener HelloServlet com.hjp.web.servlet.HelloServlet HelloServlet /HelloServlet /index.jsp
五、applicationContext.xml文件