You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DaggerContext.java 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright 2013 gitblit.com.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package com.gitblit.dagger;
  17. import javax.servlet.ServletContext;
  18. import javax.servlet.ServletContextEvent;
  19. import javax.servlet.ServletContextListener;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import dagger.ObjectGraph;
  23. /**
  24. * Dagger servlet context listener is a context listener that uses Dagger to
  25. * instantiate and inject servlets, filters, and anything else you might want.
  26. *
  27. * @author James Moger
  28. *
  29. */
  30. public abstract class DaggerContext implements ServletContextListener {
  31. public static final String INJECTOR_NAME = ObjectGraph.class.getName();
  32. protected final Logger logger = LoggerFactory.getLogger(getClass());
  33. protected abstract Object [] getModules();
  34. protected abstract void destroyContext(ServletContext context);
  35. protected ObjectGraph getInjector(ServletContext context) {
  36. Object o = context.getAttribute(INJECTOR_NAME);
  37. if (o == null) {
  38. logger.debug("instantiating Dagger modules");
  39. Object [] modules = getModules();
  40. logger.debug("getting Dagger injector");
  41. try {
  42. o = ObjectGraph.create(modules);
  43. logger.debug("setting Dagger injector into {} attribute", INJECTOR_NAME);
  44. context.setAttribute(INJECTOR_NAME, o);
  45. } catch (Throwable t) {
  46. logger.error("an error occurred creating the Dagger injector", t);
  47. }
  48. }
  49. return (ObjectGraph) o;
  50. }
  51. @Override
  52. public final void contextDestroyed(ServletContextEvent contextEvent) {
  53. ServletContext context = contextEvent.getServletContext();
  54. context.setAttribute(INJECTOR_NAME, null);
  55. destroyContext(context);
  56. }
  57. }