001/* 002 * Copyright 2012-2017 the original author or authors. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016 017package org.springframework.boot.web.servlet.support; 018 019import javax.servlet.ServletContext; 020 021import org.springframework.context.ApplicationContext; 022import org.springframework.context.ApplicationContextInitializer; 023import org.springframework.core.Ordered; 024import org.springframework.web.context.ConfigurableWebApplicationContext; 025import org.springframework.web.context.WebApplicationContext; 026 027/** 028 * {@link ApplicationContextInitializer} for setting the servlet context. 029 * 030 * @author Dave Syer 031 * @author Phillip Webb 032 * @since 2.0.0 033 */ 034public class ServletContextApplicationContextInitializer implements 035 ApplicationContextInitializer<ConfigurableWebApplicationContext>, Ordered { 036 037 private int order = Ordered.HIGHEST_PRECEDENCE; 038 039 private final ServletContext servletContext; 040 041 private final boolean addApplicationContextAttribute; 042 043 /** 044 * Create a new {@link ServletContextApplicationContextInitializer} instance. 045 * @param servletContext the servlet that should be ultimately set. 046 */ 047 public ServletContextApplicationContextInitializer(ServletContext servletContext) { 048 this(servletContext, false); 049 } 050 051 /** 052 * Create a new {@link ServletContextApplicationContextInitializer} instance. 053 * @param servletContext the servlet that should be ultimately set. 054 * @param addApplicationContextAttribute if the {@link ApplicationContext} should be 055 * stored as an attribute in the {@link ServletContext} 056 * @since 1.3.4 057 */ 058 public ServletContextApplicationContextInitializer(ServletContext servletContext, 059 boolean addApplicationContextAttribute) { 060 this.servletContext = servletContext; 061 this.addApplicationContextAttribute = addApplicationContextAttribute; 062 } 063 064 public void setOrder(int order) { 065 this.order = order; 066 } 067 068 @Override 069 public int getOrder() { 070 return this.order; 071 } 072 073 @Override 074 public void initialize(ConfigurableWebApplicationContext applicationContext) { 075 applicationContext.setServletContext(this.servletContext); 076 if (this.addApplicationContextAttribute) { 077 this.servletContext.setAttribute( 078 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 079 applicationContext); 080 } 081 082 } 083 084}