15

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?

Community
  • 1
  • 1
yegor256
  • 102,010
  • 123
  • 446
  • 597

1 Answers1

32

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

jmj
  • 237,923
  • 42
  • 401
  • 438
  • 1
    Just a note, for xhtml JSF translates _foo to getFoo and setFoo, for managed di you actually need get_foo and set_foo! – Rob Dec 27 '12 at 10:06
  • 2
    Other note> For only injection only a setter is required. Ref> http://www.mkyong.com/jsf2/injecting-managed-beans-in-jsf-2-0/ – Sergio Oct 28 '13 at 15:03