2016-07-18 26 views
1

我有一個Web應用程序讀取查詢參數。它使用該參數從外部應用程序源獲取一些數據。該Web應用程序是一個簡單的Servlet:JavaEE CDI注入 - 無法注入HttpServletRequest /響應

@WebServlet(name = "SomethingServlet", urlPatterns = {"/"}, loadOnStartup = 0) 
public class SomethingServlet extends HttpServlet { 

    @Inject 
    InterfaceOfDesire objectOfDesire; 

    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 
     objectOfDesire.doSomething(); 
    } 
} 

InterfaceOfDesire是(atm)實現一次的接口。所以不應該有歧義。

public interface InterfaceOfDesire { 
    void doSomething(); 
} 


public class ClassOfDesire implements InterfaceOfDesire { 
    @Override 
    public void doSomething() { 
     // do something very cool 
    } 
} 

最後,但並非最不重要的還有它解決了一種實現類的解析器(ATM只有1人)

public class SomethingResolver { 
    @Inject 
    private HttpServletRequest request; 
    @Inject 
    private HttpServletResponse response; 

    @Inject 
    public SomethingResolver(ServletContext servletContext) { 
     // do something with the servlet context 
    } 

    @Produces 
    public InterfaceOfDesire getInstance() { 
     // do something with request and response 
     // afterwards return object 
     return new ClassOfDesire(); 
    } 
} 

現在我得到的錯誤

WELD-001408: Unsatisfied dependencies for type HttpServletResponse with qualifiers @Default 

什麼時我做錯了?

+0

您是否在使用具有'@ Named' +範圍註釋('@ ApplicationScoped'等)的'@ Inject'標記了您的類?不要忘記'ViewScoped'和'SessionScoped'需要實現' Serializable'。 – Milkmaid

+0

你要部署什麼容器?包含版本。 –

回答

0

我會說豆(SomethingResolver)需要以某種方式綁定到HTTP請求或其會話。只有這樣它才能訪問HttpServletRequest(或響應)。

嘗試使用@RequestScoped對其進行註釋。 @SessionScoped也可能工作。

這背後的原因是你現在擁有它的方式,bean的生命週期沒有被綁定到請求 - 它可能比請求更長。 CDI無法告訴哪個servlet請求會被注入。