2 Replies Latest reply on Nov 25, 2017 2:15 PM by Wolf-Dieter Fink

    CDI injection into servlets

    Steve Brenneis Newbie

      I am having problems with CDI injection into a couple of servlets. I find mention on Google that people have problems with it, but I can't find anywhere that it is prohibited.

       

      What I have:

       

      @Qualifier

      @Retention(RUNTIME)

      @Target({ TYPE, FIELD, METHOD })

      public @interface MyAnnotation {

      }

       

      public interface MyInterface {

      ...

      }

       

      @MyAnnotation

      @ApplicationScoped

      public class MyBean implements MyInterface {

      ...

      }

       

      @WebServlet("MyResource")

      public class MyServlet extends HttpServlet {

       

      @Inject @MyAnnotation

      private MyInterface bean;

      ...

      }

       

      public class AnotherClass {

       

         @Inject @MyAnnotation

         private MyInterface bean;

      ...

      }

       

      This is packaged in an ear file with the annotation, interface, and bean in an EJB archive and the servlet in a war file. The EJB archive has an empty beans.xml with bean discover mode = all.

       

      The problem is that bean (in the servlet) is always null in the doGet method. If I remove the interface and change MyBean to a singleton no-interface bean and use @EJB injection in the servlet, Wildfly complains that there is already a MyBean implementation in the module. If I remove the @Singleton annotation from the bean, Wildfly is happy, but obviously the bean isn't application scoped and the expected state is not present.