4 Replies Latest reply on Jul 8, 2010 10:12 AM by dan.j.allen

    Inject ServletContext into managed bean

    ruslanfg
      Is it possible to inject ServletContext into managed bean?

      I`ve created @Singleton ServletContextListener
      implementation which have producer method

      @Producer @Depended
      public ServletContext getServletContext()

      I getting error: "Injection point has unstatisfied dependencies".

        • 1. Re: Inject ServletContext into managed bean
          gavin.king

          That's probably not going to work because a ServletContextListener can't be a singleton bean. (The servlet container will instantiate its own special instance.


          However, the ServletContextListener can inject a singleton bean with a producer method, and set an attribute, so you can implement it that way instead.


          Note that stuff like this can be implemented more elegantly as a portable Extension.

          • 2. Re: Inject ServletContext into managed bean
            ruslanfg

            @Inject ServletContext is not working with ServletContextListener.


            Here is test for vanilla Tomcat 6.0.20.


            My servlet listener is called before Weld.
            I have disabled tomcat specific WeldLifecycleListener.


            I assume it is unable to locate bean for ServletContextListener instance.
            But it does not work even if I make @Produces getServletContext() method static.

            • 3. Re: Inject ServletContext into managed bean
              nickarls

              It's not committed yet but I've written a simple ServletListener event -> CDI bridge, with that you could pick up the servlet context and stick it somewhere convenient.


              You can do the same thing by obtaining a BeanManager from JNDI in your servlet listener and fire a qualified event with the servlet event as payload, I think

              • 4. Re: Inject ServletContext into managed bean
                dan.j.allen

                The Seam 3 Servlet module now provides a producer for both the HttpServletRequest and HttpSession, in the class HttpServletEnvironmentProducer