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;
-
-
- public class AbstractServlet extends HttpServlet {
- private static final long serialVersionUID = 1L;
-
-
- public AbstractServlet() {
- super();
-
- }
-
- public void init(ServletConfig config) throws ServletException {
- // 在 servlet的 init method中,,寫下面的程式,讓 spring 去 ApplicationContext 做 lookup,
- SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
- config.getServletContext());
- }
-
-
- protected void doGet(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- }
-
-
- protected void doPost(HttpServletRequest request,
- HttpServletResponse response) throws ServletException, IOException {
- doGet(request, response);
- }
-
- }
然后需要有注解spring管理的bean的servlet或fiter时候继承此类,重写方法
将spring管理的bean使用注解的方式注入到servlet中
原文:http://www.cnblogs.com/jianwei-dai/p/5829836.html