1. /*
  2. * Copyright 2002-2004 the original author or authors.
  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 org.springframework.web.context.support;
  17. import javax.servlet.ServletContext;
  18. import org.apache.commons.logging.Log;
  19. import org.apache.commons.logging.LogFactory;
  20. import org.springframework.beans.BeansException;
  21. import org.springframework.beans.factory.config.BeanPostProcessor;
  22. import org.springframework.web.context.ServletContextAware;
  23. /**
  24. * BeanPostProcessor implementation that passes the ServletContext to
  25. * beans that implement the ApplicationContextAware or ResourceLoaderAware
  26. * interfaces. If both are implemented, the latter is satisfied first.
  27. *
  28. * <p>Web application contexts will automatically register this with their
  29. * underlying bean factory. Applications do not use this directly.
  30. *
  31. * @author Juergen Hoeller
  32. * @since 12.03.2004
  33. * @see org.springframework.web.context.ServletContextAware
  34. * @see org.springframework.web.context.support.XmlWebApplicationContext#postProcessBeanFactory
  35. */
  36. public class ServletContextAwareProcessor implements BeanPostProcessor {
  37. protected final Log logger = LogFactory.getLog(getClass());
  38. private final ServletContext servletContext;
  39. /**
  40. * Create a new ServletContextAwareProcessor for the given context.
  41. */
  42. public ServletContextAwareProcessor(ServletContext servletContext) {
  43. this.servletContext = servletContext;
  44. }
  45. public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
  46. if (bean instanceof ServletContextAware) {
  47. if (logger.isDebugEnabled()) {
  48. logger.debug("Invoking setServletContext on ServletContextAware bean '" + name + "'");
  49. }
  50. ((ServletContextAware) bean).setServletContext(this.servletContext);
  51. }
  52. return bean;
  53. }
  54. public Object postProcessAfterInitialization(Object bean, String name) {
  55. return bean;
  56. }
  57. }