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

来源:互联网 发布:北九州监禁杀人案知乎 编辑:程序博客网 时间:2024/06/02 04:11

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

阅读全文
0 0
原创粉丝点击