• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (C) 2007 Google Inc.
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 
17 package com.google.inject.servlet;
18 
19 import com.google.inject.Injector;
20 
21 import java.lang.ref.WeakReference;
22 
23 import javax.servlet.ServletContext;
24 import javax.servlet.ServletContextEvent;
25 import javax.servlet.ServletContextListener;
26 
27 /**
28  * As of Guice 2.0 you can still use (your subclasses of) {@code GuiceServletContextListener}
29  * class as a logical place to create and configure your injector. This will ensure the injector
30  * is created when the web application is deployed.
31  *
32  * @author Kevin Bourrillion (kevinb@google.com)
33  * @since 2.0
34  */
35 public abstract class GuiceServletContextListener
36     implements ServletContextListener {
37 
38   static final String INJECTOR_NAME = Injector.class.getName();
39 
contextInitialized(ServletContextEvent servletContextEvent)40   public void contextInitialized(ServletContextEvent servletContextEvent) {
41     final ServletContext servletContext = servletContextEvent.getServletContext();
42 
43     // Set the Servletcontext early for those people who are using this class.
44     // NOTE(dhanji): This use of the servletContext is deprecated.
45     GuiceFilter.servletContext = new WeakReference<ServletContext>(servletContext);
46 
47     Injector injector = getInjector();
48     injector.getInstance(InternalServletModule.BackwardsCompatibleServletContextProvider.class)
49         .set(servletContext);
50     servletContext.setAttribute(INJECTOR_NAME, injector);
51   }
52 
contextDestroyed(ServletContextEvent servletContextEvent)53   public void contextDestroyed(ServletContextEvent servletContextEvent) {
54     ServletContext servletContext = servletContextEvent.getServletContext();
55     servletContext.removeAttribute(INJECTOR_NAME);
56   }
57 
58   /**
59    * Override this method to create (or otherwise obtain a reference to) your
60    * injector.
61    */
getInjector()62   protected abstract Injector getInjector();
63 }
64