2017-04-27 100 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