zoukankan      html  css  js  c++  java
  • 将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时候继承此类,重写方法

  • 相关阅读:
    Nginx的安装与部署
    什么是Nginx?为什么使用Nginx?
    spark 中的RDD编程 -以下基于Java api
    java反射
    POST-GET请求
    Spring Boot 专栏
    【Shiro】Apache Shiro架构之身份认证(Authentication)
    maven项目如何启动运行---发布到tomcat中
    一位资深程序员大牛给予Java初学者的学习路线建议
    SSM框架——详细整合教程(Spring+SpringMVC+MyBatis)
  • 原文地址:https://www.cnblogs.com/jianwei-dai/p/5829836.html
Copyright © 2011-2022 走看看