001    // Copyright 2006 Howard M. Lewis Ship
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package com.javaforge.tapestry.spring;
016    
017    import javax.servlet.ServletContext;
018    import javax.servlet.http.HttpServlet;
019    
020    import org.apache.hivemind.ApplicationRuntimeException;
021    import org.apache.hivemind.lib.SpringBeanFactoryHolder;
022    import org.apache.tapestry.services.ApplicationInitializer;
023    import org.springframework.beans.factory.BeanFactory;
024    import org.springframework.web.context.WebApplicationContext;
025    
026    /**
027     * Initializes the DefaultSpringBeanFactoryHolder service with a proper bean factory, obtained from
028     * the {@link com.javaforge.tapestry.spring.ApplicationContextSource}.
029     * 
030     * @author Howard M. Lewis Ship
031     */
032    public final class SpringApplicationInitializer implements ApplicationInitializer
033    {
034        private SpringBeanFactoryHolder _beanFactoryHolder;
035    
036        /** Obtains the BeanFactory from the source and informs the BeanFactory holder about it. */
037        public void initialize(HttpServlet servlet)
038        {
039            ServletContext context = servlet.getServletContext();
040    
041            BeanFactory beanFactory = (BeanFactory) context
042                    .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
043    
044            if (beanFactory == null)
045                throw new ApplicationRuntimeException(SpringMessages.springContextIsNull());
046    
047            _beanFactoryHolder.setBeanFactory(beanFactory);
048        }
049    
050        /** For injection. */
051        public final void setBeanFactoryHolder(SpringBeanFactoryHolder beanFactoryHolder)
052        {
053            _beanFactoryHolder = beanFactoryHolder;
054        }
055    }