JSF – Eager CDI beans

Everybody knows eager managed beans in JSF 2. @ManagedBean has an eager attribute. If eager=’true’ and the scope is application, then this bean must be created when the application starts and not during the first reference to the bean. This is a nice feature when you want to load application scoped data (e.g. some select items for menus) during application startup in order to increase the performance at runtime.
 
 
 
 
 
 

@ManagedBean(eager=true)
@ApplicationScoped
public class GlobalBean {
    ...
}

@ManagedBean annotation will be deprecated with JSF 2.2. It is highly recommended to use CDI (context dependency injection) beans in JEE environment. But what is the equivalent to the eager managed beans in CDI? Well, CDI is flexible, you can write portable CDI extensions. I asked Thomas Andraschko how to do this. Thomas is a CDI expert, co-owner of PrimeFaces Extensions and the committer in OpenWebBeans (OWB) project. His tip was to implement such extension as follows:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE})
public @interface Eager
{
}
package mydomain.mypackage;

import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.event.Observes;
import javax.enterprise.inject.spi.AfterDeploymentValidation;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.Extension;
import javax.enterprise.inject.spi.ProcessBean;

public class EagerExtension implements Extension {
    private List<Bean<?>> eagerBeansList = new ArrayList<Bean<?>>();

    public <T> void collect(@Observes ProcessBean<T> event) {
        if (event.getAnnotated().isAnnotationPresent(Eager.class)
            && event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) {
            eagerBeansList.add(event.getBean());
        }
    }

    public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) {
        for (Bean<?> bean : eagerBeansList) {
            // note: toString() is important to instantiate the bean
            beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString();
        }
    }
}

The extensions should be registered in a file META-INF/services/javax.enterprise.inject.spi.Extension. The file has only one line with a fully qualified path to the EagerExtension class, e.g. mydomain.mypackage.EagerExtension. Using is simple. Assume, we have an application scoped LayoutController CDI bean which is responsible for the entire layout configration. We can annotate it with @Eager and speed up the layout creation.

@ApplicationScoped
@Eager
@Named
public class LayoutController implements Serializable {
    private LayoutOptions layoutOptions;

    @PostConstruct
    protected void initialize() {
        layoutOptions = new LayoutOptions();

        LayoutOptions panes = new LayoutOptions();
        panes.addOption('slidable', false);
        panes.addOption('spacing', 6);
        layoutOptions.setPanesOptions(panes);

        ...
    }

    public LayoutOptions getLayoutOptions() {
        return layoutOptions;
    }
}

Have fun with CDI!
 

Reference: JSF – Eager CDI beans from our JCG partner Oleg Varaksin at the Thoughts on software development blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

3 Responses to "JSF – Eager CDI beans"

  1. Bill B. says:

    In NetBeans 7.3, your code:

    @Qualifier
    @Retention(RetentionPolicy.RUNTIME)
    @Target({TYPE})
    public @interface Eager
    {
    }

    Causes the following error:

    The CDI Annotation is declared as Qualifier but it has wrong target values. Correct target values are ‘{METHOD, FIELD, PARAMETER, TYPE’} or ‘{FIELD, PARAMETER’}.

    Anybody got a fix or a work-around?

    Thanks, Bill

  2. tdr says:

    Hi this was a very informative article. I’ve never dealt with extensions before. I”m just now becoming familar with CDI. I followed these instructions exactly — I’m building a Map to be used as a select list in a search page and I want it initialized while the app is being deployed. I’d previously implemented it as an eager=true @ManagedBean before I switched from JSF2 to CDI.
    I’m getting this error now during deployment
    WELD-001408 Unsatisfied dependencies for type [StateList] with qualifiers [@Default] at injection point [[field] @Inject gov.ssa.dne.nmst.view.Search.stateList]
    I can’t understand which unsatisfied dependencies it’s refering to.

  3. Pete says:

    I followed the code to the letter but the Collect method is not scanning my classes. It does scan something like 53 classes in org.jboss.weld.bean and in com.sun.jersey.server.impl.cdi. I tried everything I could think of to no avail. I’m stuck… Any suggestions?

Leave a Reply


7 × eight =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close