Spring MVC: Inject ServletContext into bean 

Joined:
08/13/2009
Posts:
172

May 17, 2012 19:31:39    Last update: May 17, 2012 19:31:39
To inject ServletContext into a Spring bean:
  1. implement ServletContextAware:
    import javax.servlet.ServletContext;
    
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import org.springframework.web.context.ServletContextAware;
    
    public class MyBean implements ServletContextAware {
    
        private static final Logger logger = LoggerFactory.getLogger(MyBean.class);
    
        private ServletContext ctx;
    
        public void setServletContext(ServletContext ctx) {
    	logger.info("ServletContext: " + ctx);
    	this.ctx = ctx;
        }
    }
    

  2. Define bean in Spring application context:
    <beans:bean id="myBean"
       class="com.example.MyBean"/>
    

Share |
| Comment  | Tags