在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中注入成功