Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject entire managed bean via @ManagedProperty annotation?

I'm trying to inject entire JSF managed bean into another managed bean by means of @ManagedProperty annotation (very similar to Possible to inject @ManagedBean as a @ManagedProperty into @WebServlet?, but I'm injecting into a bean, not a servlet). This is what I'm doing:

@ManagedBean
public class Foo {
  @ManagedProperty(value = "#{bar}")
  private Bar bar;
}

@ManagedBean
public class Bar {
}

Doesn't work (JSF 2.0/Mojarra 2.0.3):

SEVERE: JSF will be unable to create managed bean foo when it is 
requested.  The following problems where found:
- Property bar for managed bean foo does not exist. Check that 
  appropriate getter and/or setter methods exist.

Is it possible at all or I need to do this injection programmatically via FacesContext?

like image 962
yegor256 Avatar asked Mar 02 '11 09:03

yegor256


People also ask

What is managed bean annotation?

bean. ManagedBean) annotation in a class automatically registers that class as a resource with the JavaServer Faces implementation. Such a registered managed bean does not need managed-bean configuration entries in the application configuration resource file.

What scopes are available for a managed bean?

You can use following scopes for a bean class: Application (@ApplicationScoped): Application scope persists across all users? interactions with a web application. Session (@SessionScoped): Session scope persists across multiple HTTP requests in a web application.

What is the difference between managed bean and backing bean in JSF?

1) BB: A backing bean is any bean that is referenced by a form. MB: A managed bean is a backing bean that has been registered with JSF (in faces-config. xml) and it automatically created (and optionally initialized) by JSF when it is needed.

What is managed bean in JSF JavaServer faces?

JavaServer Faces (JSF) Managed Bean is a regular Java Bean class registered with JSF. In other words, Managed Beans is a Java bean managed by JSF framework. Managed bean contains the getter and setter methods, business logic, or even a backing bean (a bean contains all the HTML form value).


1 Answers

You need to add setters and getters

@ManagedBean
public class Foo {
  @ManagedProperty(value = "#{bar}")
  private Bar bar;
  //add setters and getters for bar
  public Bar getBar(){
      return this.bar;
  }
  public void setBar(Bar bar){
      this.bar = bar;;
  }
}

When the FacesContext will resolve and inject dependencies it will use setters injection so appropriate setters/getters should be there.otherwise it won't find the property

like image 184
jmj Avatar answered Oct 09 '22 21:10

jmj