很多情况在进行Web开发的时候需要自己手写Servlet来完成某些功能,而servlet有需要注入Spring容器中的某些bean,这是每次都要手动获取比较麻烦,这里有一个解决方案,只需要写一个servlet的基类,其它的类只需要集成基类后,便可以想action那样进行注入了。
基类Servlet代码如下:
1 public class BaseServlet extends HttpServlet { 2 private static final long serialVersionUID = 1L; 3 4 public void init() throws ServletException { 5 super.init(); 6 WebApplicationContextUtils 7 .getWebApplicationContext(getServletContext()) 8 .getAutowireCapableBeanFactory().autowireBean(this); 9 } 10 11 }
具体的功能servlet代码如下:
1 @WebServlet("/testServlet") 2 public class TestServlet extends BaseServlet { 3 4 private static final long serialVersionUID = 1L; 5 @Autowired 6 private TestService testService = null; 7 8 protected void doGet(HttpServletRequest request, 9 HttpServletResponse response) throws ServletException, IOException { 10 testService.print(); 11 } 12 13 protected void doPost(HttpServletRequest request, 14 HttpServletResponse response) throws ServletException, IOException { 15 doGet(request, response); 16 } 17 }
其中testServic属性便是自动注入的。具体的spring配置注入不再细说。