JSF2 View Scope with Spring Core

Working with Spring and JSF2 I encountered the need to use something like a ViewScope bean.

The Spring Framework support the following scopes bean scopes:

  • singleton
  • prototype
  • request
  • session
  • globalSession

Adding a new scope is quite simple using Spring. To add the View Scope in the Spring IoC container it is necessary to create a custom scope which implements the org.springframework.beans.factory.config.Scope interface and register it with the Spring Custom Scope Configurer.



ViewScope implementation


package eu.ac.tutorial.spring.scope;

import java.util.Map;
import javax.faces.context.FacesContext;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;

public class ViewScope implements Scope {

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

        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;
        }

    }

    @Override
    public String getConversationId() {
        return null;
    }

    @Override
    public void registerDestructionCallback(String arg0, Runnable arg1) {

    }

    @Override
    public Object remove(String name) {

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

    }

    @Override
    public Object resolveContextualObject(String arg0) {
        return null;
    }

}



Spring Configuration


<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="view">
                <bean class="eu.ac.tutorial.spring.scope.ViewScope"/>
            </entry>
        </map>
    </property>
</bean>



Usage


Now you can use it:

package eu.ac.tutorial.spring.web;

import javax.inject.Named;
import org.springframework.context.annotation.Scope;

/**
* ContactListPage JSF backing bean.
*/
@Component("contacListView")
@Scope("view")
public class ContactListView {

   @Autowire
   private ContactService contactService;

   public ContactListView() {
   }

   // etc…
}

Comments

Popular posts from this blog

WebSphere stdout/stderr logging redirect

Spring Data Repositories: Query by Specification