001/* 002 * Copyright 2002-2012 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 * https://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.web.context.support; 018 019import javax.servlet.ServletContext; 020 021import org.springframework.beans.factory.FactoryBean; 022import org.springframework.web.context.ServletContextAware; 023 024/** 025 * {@link FactoryBean} that retrieves a specific ServletContext init parameter 026 * (that is, a "context-param" defined in {@code web.xml}). 027 * Exposes that ServletContext init parameter when used as bean reference, 028 * effectively making it available as named Spring bean instance. 029 * 030 * <p><b>NOTE:</b> As of Spring 3.0, you may also use the "contextParameters" default 031 * bean which is of type Map, and dereference it using an "#{contextParameters.myKey}" 032 * expression to access a specific parameter by name. 033 * 034 * @author Juergen Hoeller 035 * @since 1.2.4 036 * @see org.springframework.web.context.WebApplicationContext#CONTEXT_PARAMETERS_BEAN_NAME 037 * @see ServletContextAttributeFactoryBean 038 */ 039public class ServletContextParameterFactoryBean implements FactoryBean<String>, ServletContextAware { 040 041 private String initParamName; 042 043 private String paramValue; 044 045 046 /** 047 * Set the name of the ServletContext init parameter to expose. 048 */ 049 public void setInitParamName(String initParamName) { 050 this.initParamName = initParamName; 051 } 052 053 @Override 054 public void setServletContext(ServletContext servletContext) { 055 if (this.initParamName == null) { 056 throw new IllegalArgumentException("initParamName is required"); 057 } 058 this.paramValue = servletContext.getInitParameter(this.initParamName); 059 if (this.paramValue == null) { 060 throw new IllegalStateException("No ServletContext init parameter '" + this.initParamName + "' found"); 061 } 062 } 063 064 065 @Override 066 public String getObject() { 067 return this.paramValue; 068 } 069 070 @Override 071 public Class<String> getObjectType() { 072 return String.class; 073 } 074 075 @Override 076 public boolean isSingleton() { 077 return true; 078 } 079 080}