Servlet获取Spring bean

场景:

有时在servlet中需要使用Spring bean,如上传图片等

处理方法:

重写Servlet的init方法,通过WebApplicationContextUtils获得,代码如下:

public void init() throws ServletException {          
        super.init();
        ServletContext servletContext = this.getServletContext();  
        WebApplicationContext ctx =    WebApplicationContextUtils.getWebApplicationContext(servletContext);
        bean = (TestBean)ctx.getBean("beanid");
    }
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	   throws ServletException, IOException {
	   ......
	   bean.save(signpic);
	   ......
	}
}

你可能感兴趣的:(Servlet获取Spring bean)