Monday, November 25, 2013


Custom Managed Bean Scopes

The JSF 2.0 specification has added custom scopes for managed beans.  I think this is something that will be quite useful to extension developers (think homegrown conversation scopes). 

In previous versions of JSF, managed bean scopes were restricted to applicationsessionrequest, and none.  JSF 2.0 adds one new custom scope called 'view' which I've touched on in previous blog entries.  But how does support for non-standard scopes work?

It's pretty simple actually.  The custom scope can be referenced in the managed-bean-scope element of the faces-config.xml or via the @CustomScoped annotation.  The value for this scope, in either the xml or annotation case, must be an EL expression that resolves to a Map.

For example, if you reference this custom scope using the 'managed-bean-scope' in xml, it could look something like:


   bean
   somepackage.Bean
   #{customScope}


If you're into using the annotations, then the @CustomScoped annotation might look like:

@CustomScoped(value="#{customScope}")

The managed bean facility in 2.0 will use the expression to resolve the Map that backs the custom scope.  If the Map doesn't already contain the bean, the managed bean facility will create the bean and push it to the custom scope for you.

This new functionality is available as of last night's build of Mojarra 2.0.0.

I've also written a simple example that shows how to write an ELResolver to resolve/manage a custom scope.
UPDATE (April 15, 2009 1:50 PM-ish)
The example has been updated to show how to use the PostConstructCustomScopeEvent andPreDestroyCustomScopeEvent system events.  PreDestroyCustomScopeEvent is particularly import for custom scope authors to publish if they want managed bean methods annotated with @PreDestroy to be invoked.

No comments: