2
votes

In a container environment (such as wildfly, jboss), are servlets treated as Managed bean? i.e. Can I inject the Servlet into any other CDI bean?

I use CdiRunner CDI-Unit to write my tests. And therefore I would like to inject Servlet into my Test class and test its (public) methods.

1
I believe a servlet is not considered a managed bean and it runs in the servlet container like a managed bean runs in the bean container. You should however be able to inject the servlets context into your test class? This might provide some help. - JGlass
@JGlass The cdi-unit source code is a good spot. However, be careful with the other link: it points to the old and descontinued JBoss Seam framework documentation. I recommend the CDI specification for reference instead. - cassiomolin
@cassio-mazzochi-molin, thank you for the positive feedback and warning, I'd edit the comment if I could but it does'nt look like I can. - JGlass

1 Answers

2
votes

The lifecycle of a servlet if managed by the servlet container and not by CDI. However, CDI injection is expected to work in servlets.

A servlet container will also provide some built-in beans that can be injected using CDI:

A servlet container must provide the following built-in beans, all of which have qualifier @Default:

  • a bean with bean type javax.servlet.http.HttpServletRequest, allowing injection of a reference to the HttpServletRequest

  • a bean with bean type javax.servlet.http.HttpSession, allowing injection of a reference to the HttpSession

  • a bean with bean type javax.servlet.ServletContext, allowing injection of a reference to the ServletContext

If you need to inject a servlet somewhere, you are probably doing something wrong.