You have two basic options for making injected variables available to a servlet init method:
1. Let your servlet container (i.e, Tomcat, Jetty, etc.) manage the servlet lifetime * create your injector somehow (probably in a ServletContextListener) * provide the injector to the Servlet (probably as data in the ServletContext) * inject the missing data in the servlet (using injector.injectMembers(this)). This approach only allows field or method injection, and calling the injector will need to be the first job of your init method. 2. Let Guice manage the servlet lifetime using Guice Servlet. * create your injector in a subclass of GuiceServletContextListener, with your modules. * configure GuiceFilter as a filter * (usually) create a catch-all servlet that logs or does nothing, to ensure the filter is run. This approach lets you use any form of injection in the servlet, which will then be ready when init is called. Guice does the heavy lifting for you. On Fri, Apr 29, 2011 at 2:52 PM, garey <[email protected]> wrote: > Hi - > > I have a class that needs a database connection, so I have > provides method in a module and I have a constructor like this > > class A { > > @Inject > A(Connection c) { ...} > > ... > } > > now I have an init method in a servlet that I call if I want to > initialize an A. The method requires some parameters, so I do > > public void init( <parameters>) { > @Inject A a; > > ... > } > > but I get a compile time error telling me that I cannot use @Inject in > this way. What fundamental concept am I not getting (this time)? > > Thanks for any help; > > Garey Mills > > -- > You received this message because you are subscribed to the Google Groups > "google-guice" group. > To post to this group, send email to [email protected]. > To unsubscribe from this group, send email to > [email protected]. > For more options, visit this group at > http://groups.google.com/group/google-guice?hl=en. > > -- You received this message because you are subscribed to the Google Groups "google-guice" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
