Servlet 類中使用@autowire 注入使用bean

在Servlet類中,我們有時候需要使用sping中的某些bean對象,但是當我們使用時,會發現注入失敗。
解決方法如下所示:

public class BaseServlet extends HttpServlet {

    public void init() throws ServletException {
        WebApplicationContextUtils
                .getWebApplicationContext(getServletContext())
                .getAutowireCapableBeanFactory().autowireBean(this);
    }

}

具體的Servlet功能如下:

@WebServlet("/userServlet")
public class UserServlet extends BaseServlet {

    @Autowired
    private UserService userService;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        userService.dotest();
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

此時,再次測試,便可發現,spring中的bean對象在Servlet中注入成功

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章