您的位置:首页 > 其它

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

2017-10-18 16:51 330 查看
在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中注入成功
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: