Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
titleSessionBackedBeanFactory.java
borderStylesolid
package net.itneering.core.spring.session;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;

import com.opensymphony.xwork.ActionContext;

import java.util.Map;
import java.io.Serializable;

/**
 * SessionBackedBeanFactory tries to lookup beans by name in XWork session. If not found,
 * it tries to instantiate new bean and attaches it to said session.
 *
 * @author <a href="mailto:gielen@it-neering.net">Rene Gielen</a>
 */

public abstract class SessionBackedBeanFactory implements BeanFactoryAwareSerializable, SessionProxyBeanFactoryAware {

    BeanFactory beanFactory = null;

    /**
     * Find a component by name in session scoped storage implementation. If not found, try to instantiate new one by
     * {@link org.springframework.beans.factory.BeanFactory#getBean(String)}. Then found component will be attached
     * to session store implementation.
     *
     * @param componentName
     * @return The requested component, if found.
     */
    public Object getSessionComponent( String componentName ) {
        Object result = getSession().get(componentName);
        if ( result == null ) {
            result = beanFactory.getBean(componentName);
            storeComponent(componentName, result);
        }
        return result;
    }

    public void storeComponent(String componentName, Object component ) {
        getSession().put(componentName, component);
    }

    /**
     * Actual implementation of the session scoped storage Map.
     * Lookup {@link com.opensymphony.xwork.ActionContext#getSession()}.
     *
     * @return The Map for keeping session objects.
     */
    public Map getSession() {
        return ActionContext.getContext().getSession();
    }

    /**
     * Callback that supplies the owning factory to a bean instance.
     * <p>Invoked after population of normal bean properties but before an init
     * callback like InitializingBean's afterPropertiesSet or a custom init-method.
     *
     * @param beanFactory owning BeanFactory (may not be null).
     *                    The bean can immediately call methods on the factory.
     *
     * @throws org.springframework.beans.BeansException
     *          in case of initialization errors
     * @see org.springframework.beans.factory.BeanInitializationException
     */
    public void setBeanFactory( BeanFactory beanFactory ) throws BeansException {
        this.beanFactory = beanFactory;
    }
}

...