标题:在SpringMVC容器中Servlet如何调用Service层接口?
直接最简单有效的方法,重写Servlet的Init()方法。代码如下:
1)、 首先新建一个重写Servlet的Init()方法的类继承HttpServlet
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; /** * 描述:Servlet重写Init()方法 * @author WangKun */ public class ServletProxy extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; public void init() throws ServletException { super.init(); WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); AutowireCapableBeanFactory factory = wac.getAutowireCapableBeanFactory(); factory.autowireBean(this); } } 2)、新建自己需要的Servlet再继承重写Servlet的类 ( ServletProxy) import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; public class ***Servlet extends ServletProxy { @Autowired private ***Service ***Service; private static final long serialVersionUID = 2827297299439162553L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws Exception { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws Exception { ***Service.自己的接口方法。 你自己的东西自己写了。 } }