Spring Boot:将Bean注入HttpServlet

hel*_*hod 5 spring spring-boot

我有一个Spring Boot,我已经自动配置了一个Router bean.这一切都很完美但是当我想将bean注入自定义servlet时它会成为一个问题:

public class MembraneServlet extends HttpServlet {
    @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该是要走的路,但是

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
Run Code Online (Sandbox Code Playgroud)

不会自动装配路由器,因为WebapplicationContext它始终为空.该应用程序在MVC环境中运行.

Sta*_*007 5

假设您将 Spring 应用程序上下文连接到 Servlet 上下文,您可能希望将 ServletContext 传递给SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext

public class MembraneServlet extends HttpServlet {

  @Autowired
    private Router router;

    @Override
    public void init() throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this, getServletContext());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        new HttpServletHandler(req, resp, router.getTransport()).run();
    }
}
Run Code Online (Sandbox Code Playgroud)