JSF Managed bean and managed property both necessary?

Mark W picture Mark W · Dec 6, 2013 · Viewed 21.1k times · Source

I'm new to JSF and was wondering:

If I have a controller that handles all the work for a given page and a bean that holds all the data for said page, is It necessary to have both the

@ManagedProperty(value="#{myBean}") 

annotation on the controller and the

@ManagedBean(name="myBean")
@SessionScoped

annotations on the form bean?

Answer

Adarsh picture Adarsh · Dec 6, 2013

Managed beans in JSF are used to store the state of a web page. The JSF implementation is responsible for creating and discarding the bean objects( hence the name managed bean).

For every class you write @ManagedBean, the bean object is created by the JSF implementation as and when it detects an usage of the bean with the name(you can either sepcify a bean name or leave it to JSF to use the default name-class name with the first character changed to lowercase). The object created is placed in a map of the specified scope. Each scope has a map that it uses to store bean objects which have that scope specified.

Now if you need the values of these beans in your controller, you have to inject it using the ManagedProperty annotation. Note that you would need to provide the controller with a setter method for the managedProperty.

So to answer your question, the managedBean annotation is required to tell the JSF implementation to manage the bean instance and store the values in the table specific to the session scope. And the ManagedProperty annotation is needed to use that bean stored in the current session so that you can access all of its values.