将spring管理的bean使用注解的方式注入到servlet中
Filter和Servlet中不能直接注解使用spring的bean,因为这两个都是servlet容器维护管理的,当然也有实现方法,如下:
1。创建一个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 {
- // 在 servlet的 init method中,,寫下面的程式,讓 spring 去 ApplicationContext 做 lookup,
- 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);
- }
- }
然后需要有注解spring管理的bean的servlet或fiter时候继承此类,重写方法
种桃道士归何处,前度刘郎今又来。