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