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