Main Tutorials

Injecting Managed beans in JSF 2.0

In JSF 2.0, a new @ManagedProperty annotation is used to dependency injection (DI) a managed bean into the property of another managed bean.

Let see a @ManagedProperty example :

MessageBean.java – A managed bean named “message“.


import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean(name="message")
@SessionScoped
public class MessageBean implements Serializable {

	//business logic and whatever methods...

}

HelloBean.java – Inject the “message” bean into the “messageBean” property.


import java.io.Serializable;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class HelloBean implements Serializable {

	@ManagedProperty(value="#{message}")
	private MessageBean messageBean;

	//must povide the setter method
	public void setMessageBean(MessageBean messageBean) {
		this.messageBean = messageBean;
	}

	//...
}

In this example, it uses the @ManagedProperty annotation to DI the “message” bean (MessageBean.java) into the property (messageBean) of the “hello” bean (HelloBean.java) via setter method, setMessageBean().

Note
To make this injection successful, the inject property (messageBean) must provide the setter method.

Download Source Code

Reference

  1. ManagedProperty Javadoc
  2. JSF 2.0 : managed bean x does not exist, Check that appropriate getter and/or setter methods exist

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
24 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Sharliuska
9 years ago

Sabeis tu verga

ian
13 years ago

I agree with mkyong,
there is no problem of using sessionScoped, especially in a simple example like this.
If you have a large application and you keep using sessionScoped for all your beans than you should rethink your design.

www.vitrinelivre.com.br
4 years ago

Muito obrigado, sempre bem detalhista nas instruções.

Adnaane
8 years ago

please i can access to the value of my sessionbean(which is a sessionScoped)
please i need your help

Renan
9 years ago

thank you… very good.

nelson
9 years ago

Regards. When is a ManagedBeans and a ManagedProperty initialized?

bajrang kar
10 years ago

Can somebody show an example for injecting a Map or HashMap with @ManagedProperty.

I am getting an error like ”

javax.el.ELException: Cannot convert #{userBean.refs of type class java.lang.String to interface java.util.Map

Here I am trying to inject refs as a Map. I am unable to get the reason. Please Help.

Rogerio Coli
11 years ago

Hello Mkyong, congratulations for the excellent introductory tutorial for JSF 2. I have a question though, what is the difference of using the dependency injection or directly access another ManagedBean directly in xhtml? In this case we will be using two diferents managedBeans on the same xhtml. Thanks.

massimo
11 years ago

maybe my theory about it is still quite poor but I have noted that when i want to use data or method of the injected bean is called its constructor creating …it’s the right behaviour? what about if i want to call the same instance and not create a new one?

John
11 years ago

hi,

It’s posible injection in javax.faces.validator.Validator?

I need a DAO inside my validator for check that exist an element in the table with the same name.

Check constraint unique violation, whith hibernate an jsf.

John
11 years ago
Reply to  John

Thanks for nothing, lol

This is the solution:

@ManagedBean
@RequestScoped
public class EntityNameUniqueValidator implements javax.faces.validator.Validator, Serializable {

    public static final String VALIDATOR_ID = "entityNameUniqueValidator";
    private static Logger logger = LogManager.getLogger(EntityNameUniqueValidator.class);

    @Override
    public void validate(FacesContext facesContext, UIComponent component, Object value) throws ValidatorException {
        logger.info(String.format("Validating with this params %s %s %s", facesContext, component, value));
        ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance());
        EntityDAO entityDao = ctx.getBean("hibEntityDAO",HibEntityDAO.class);
        
        String entityName = (String) value;
        String msgError = null;
        Entity entity = null;
        try {
            entity = entityDao.getEntityByName(entityName);
        } catch (DAOException ex) {
            logger.error("Error getting validation dates");
        }
        if (entity != null) {
            logger.error("Error entity exist with the given name");
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error entity exist with the given name", "Error entity exist with the given name"));
        }
    }
}
F.Farivar
11 years ago

Hi
My question is what if the parameter sayWelcome in class MessageBean would be set through xhtml instead of setting in the class.

How would class HelloBean could access that parameter that is set and is belonged to the instantiated of class MessageBean?

This is normal problem when choosing from one dropdown menu one should result in list of certain items in 2:nd drop down menu.

Kamal Giri
11 years ago

Nice Tutorial Mkyong.
Thanks 🙂

Dragon
11 years ago

Very simple and clear. Thanks in advance.

Amine Alaoui
11 years ago

Thank you very much.

Enrique
11 years ago

I tried to use it with @Named instead of @ManagedBean but it returns null, is there another annotation to use with @Named Beans or am I doing something wrong?

Thanks in advance.

ibliss
12 years ago

IF there is no message bean instance does jsf create it not any annotation force to create?

Buddhika
12 years ago

THis was very useful to me. Thank you very much.

kasim
12 years ago

instead of @ManagedBean(name=”message”), can I use @Named(“message”)?

Note: JSF2 introduced the @ManagedBean annotation which was intended to minimise Faces configuration in XML files. Whilst this alleviates the need to declare JSF managed beans in XML it does not promote annotation consistency across all layers in the application.

ugrkrmn21
13 years ago

it i good job.Thanks mkyong.

gabriel
13 years ago

Whats wrong with sessionscoped?

melanke
13 years ago

ohh man! do you use sessionScoped? shame on you!

Buddhika
12 years ago
Reply to  melanke

This is just an example. I used that for View Scoped and it worked fine. Please don’t condemn others work like this.