JSF View scope in Spring

khan picture khan · Oct 22, 2012 · Viewed 23.9k times · Source

Is there any scope like JSF @ViewScoped in Spring 3.0? I have an application using JSF+Spring where backing beans are managed by Spring. I didn't find any scope like JSF wiew scope in Spring. I saw the blog Porting JSF 2.0’s ViewScope to Spring 3.0, but it didn't work for me.

Here's my attempt on the custom Spring scope:

import java.util.Map;

import javax.faces.context.FacesContext;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

/**
 * Implements the JSF View Scope for use by Spring. This class is registered as a Spring bean with the CustomScopeConfigurer.
*/
public class ViewScope implements Scope {

    public Object get(String name, ObjectFactory<?> objectFactory) {

        System.out.println("**************************************************");
        System.out.println("-------------------- Getting objects For View Scope ----------");
        System.out.println("**************************************************");
        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            Map<String, Object> viewMap = FacesContext.getCurrentInstance().getViewRoot().getViewMap();
            if (viewMap.containsKey(name)) {
                return viewMap.get(name);
            } else {
                Object object = objectFactory.getObject();
                viewMap.put(name, object);
                return object;
            }
        } else {
            return null;
        }
    }

    public Object remove(String name) {
        System.out.println("**************************************************");
        System.out.println("-------------------- View Scope object Removed ----------");
        System.out.println("**************************************************");

        if (FacesContext.getCurrentInstance().getViewRoot() != null) {
            return FacesContext.getCurrentInstance().getViewRoot().getViewMap().remove(name);
        } else {
            return null;
        }
    }

    public void registerDestructionCallback(String name, Runnable callback) {
        // Do nothing
    }

    public Object resolveContextualObject(String key) {         return null;
    }

    public String getConversationId() {
        return null;
    }

}

application-context.xml:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
            <map>
                <entry key="view">
                    <bean class="com.delta.beans.ViewScope"/>
                </entry>
            </map>
        </property>
 </bean>

Answer

rumatoest picture rumatoest · Apr 20, 2015

Recently I've created maven artifact which will solve this problem.

See my github javaplugs/spring-jsf repository.