office.aizaz
office.aizaz

Reputation: 191

Is Servlet a CDI/Managed Bean in Java EE

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.

Upvotes: 2

Views: 614

Answers (1)

cassiomolin
cassiomolin

Reputation: 130857

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.

Upvotes: 2

Related Questions