2017-04-27 102 views
4

我有一个Spring Boot,我已经自动配置了一个Router Bean。 这一切都可以完美运行,但是当我想对这个bean注入到一个特定的Servlet它成为一个问题:Spring Boot:将Bean注入到HttpServlet中

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(); 
    } 
} 

这应该是要走的路,但

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); 

不会自动装配的因为WebapplicationContext始终为空。该应用程序在MVC环境中运行。

+0

是你的httpservlet嵌入spring博ot? –

+0

这不是重复的https://stackoverflow.com/questions/18745770/spring-injection-into-servlet? –

+1

您是否考虑过使用'@ Controller'或'@ RestController'来代替servlet?我认为这是一种更好的方式在spring-boot中做事情的方式 –

回答

3

假设你的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(); 
    } 
} 
1

注入'Router'作为构造参数怎么样?

所以你要有这样的:

public class MembraneServlet extends HttpServlet { 

    private Router router; 

    public MembraneServlet(Router router){ 
     this.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(); 
    } 
} 

则可以编程方式创建的servlet注册是这样的:

@Bean 
public ServletRegistrationBean membraneServletRegistrationBean(){ 
    return new ServletRegistrationBean(new MembraneServlet(),"/*"); 
} 
+0

这是行不通的,因为HttpServlet没有被Spring实例化。 – helpermethod

+0

对不起,我已经复制了OP的代码,并没有删除'SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);',如果只需要''Router'',这是不必要的。 – bilak