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 the Author

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

Comments

avatar
21 Comment threads
3 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
21 Comment authors
AdnaaneSharliuskaRenannelsonbajrang kar Recent comment authors
newest oldest most voted
Sharliuska
Guest
Sharliuska

Sabeis tu verga

Adnaane
Guest
Adnaane

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

Renan
Guest
Renan

thank you… very good.

nelson
Guest
nelson

Regards. When is a ManagedBeans and a ManagedProperty initialized?

bajrang kar
Guest
bajrang kar

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.

trackback
JSF | Annotary

[…] More from Giovanny Fuentes: Oracle JavaScript Java NetBeans Sort Share http://www.mkyong.com       4 minutes […]

Rogerio Coli
Guest
Rogerio Coli

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
Guest
massimo

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
Guest
John

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
Guest
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");… Read more »

F.Farivar
Guest
F.Farivar

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
Guest
Kamal Giri

Nice Tutorial Mkyong.
Thanks :)

Dragon
Guest
Dragon

Very simple and clear. Thanks in advance.

Amine Alaoui
Guest
Amine Alaoui

Thank you very much.

Enrique
Guest
Enrique

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
Guest
ibliss

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

Buddhika
Guest
Buddhika

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

kasim
Guest
kasim

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
Guest
ugrkrmn21

it i good job.Thanks mkyong.

ian
Guest
ian

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.

gabriel
Guest
gabriel

Whats wrong with sessionscoped?

melanke
Guest
melanke

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

Buddhika
Guest
Buddhika

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