servlet 使用spring管理bean

servlet 使用spring管理bean

要serlvet使用注解的形式去注入bean,那么如何才能将spring管理的bean注入到servlet中。原本spring管理的bean和servlet不在一个上下文环境中是无法相互注入的。

解决办法创建一个AbstractServlet 抽象类,让你的所有servlet继承于此类

 

 

 

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 * Servlet implementation class AbstractServlet
 */

public class AbstractServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AbstractServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init(ServletConfig config) throws ServletException {
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
				config.getServletContext());
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 关键在于SpringBeanAutowiringSupport.processBInjectionasedOnServletContext(this,

				config.getServletContext());
通过使用spring提供的支持可以将当前的servlet上下文环境添加到spring管理的上下文环境中。
当然还有其他一些方法就不在这赘述了。

你可能感兴趣的:(spring)