Inject CDI Managed Bean

This tutorial we show you how to inject CDI managed bean into another. CDI is much more powerful then plain JSF managed beans. With JSF Managed beans you where limited to JSF beans only. But with CDI beans you have the ability to inject any Java EE CDI managed bean into another. Another powerfull feature of CDI is that it uses proxies. This means that you can inject a minor scoped bean into a larger unlike JSF.

Note:

You cannot inject a CDI managed bean into a JSF managed bean and vice versa.

Create CDI Managed Bean

We’ll inject this CDI managed bean into the other. It is important to notice that while this bean is RequestScope. So normally you should not make the bean serializable. But we are injecting this bean into a session scoped bean. Which means that this bean must also support serialazable.

package com.memorynotfound;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@RequestScoped
public class MessageBean implements Serializable {

    public String getMessage(String name){
        return "Hello, " + name;
    }
}

Inject CDI Managed Bean

The power of CDI is that you can inject every managed bean by CDI into another by using the @Inject annotation.

package com.memorynotfound;

import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.Serializable;

@Named
@SessionScoped
public class UserBean implements Serializable {

    @Inject
    private MessageBean messageBean;

    public MessageBean getMessageBean() {
        return messageBean;
    }
}

References

Download

Download it – inject-cdi-managed-bean

You may also like...