Björn Pollex
Björn Pollex

Reputation: 76778

What is the idiomatic way to get references to other managed beans?

The way I see it, there are three ways to get a reference to another bean:

  1. Using CDI, I can @Inject a named bean. This has the drawback that CDI-annotations don't mix well with faces-annotations, and thus I cannot use @ViewScoped anymore.
  2. Using @ManagedProperty seems to be ideal, apart from the fact that I have to introduce a public setter for that to work, which hurts encapsulation.
  3. I can use something like this (proposed in this answer):

    @SuppressWarnings("unchecked")
    public static <T> T findBean(String beanName) {
        FacesContext context = FacesContext.getCurrentInstance();
        return (T) context.getApplication().evaluateExpressionGet(
            context, "#{" + beanName + "}", Object.class);
    }
    

    I can use this method to initialize the properties in my @PostConstruct. This has none of the drawbacks above, but seems a little bit complicated. Why would I have to write a helper-method for something the framework should provide?

My question is, which one of the three above should I use? Also, feel free to correct any misconceptions I may have stated in the description above, or to propose other (more elegant) methods to achieve that goal.

Upvotes: 1

Views: 176

Answers (2)

Bozho
Bozho

Reputation: 597016

If you really can't god without @ViewScoed, and you want to stay only with JSF and CDI - then the 2nd. Don't worry about encapsulation for external dependencies. Even outside a faces context you will still have to somehow set the other object, so a setter is due.

If you wish to add seam to the picture, and you are using CDI anyway, then the 1st. See the jan groth's answer.

Upvotes: 3

Jan Groth
Jan Groth

Reputation: 14636

Definitely the 1st, together with Seam 3 Faces (here). Just put it in your classpath, and @Viewscoped is perfectly bridged between CDI and JSF :-) Needless to mention that CDI has the by far superior concept for dependency injection than what JSF ships with...

Upvotes: 2

Related Questions