zoukankan      html  css  js  c++  java
  • Servlet自动注入Spring容器中的Bean解决方法

    很多情况在进行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配置注入不再细说。

  • 相关阅读:
    HDU 1301 Jungle Roads
    HDU 1671 Phone List
    HDU 1992 Tiling a Grid With Dominoes
    HDU 1251 统计难题
    总结自己的近期表现
    Windows API 函数: SetClassLong
    ModifyStyle
    assert,assert_valid,verify,trace用法
    用VC++绘制位图按钮
    Codeforces 144D. Missile Silos 最短路
  • 原文地址:https://www.cnblogs.com/janken/p/5091505.html
Copyright © 2011-2022 走看看