1

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.

Community
  • 1
  • 1
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283

2 Answers2

3

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.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
2

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...

Jan Groth
  • 14,039
  • 5
  • 40
  • 55
  • +1, though I really don't like the way they decided to handle this. JSF and CDI on one side, beings standard, but in order to do something that should be available out-of-the box, you need a proprietary framework. – Bozho Jun 28 '11 at 21:51
  • Thanks for the answer. For now though, I want to keep it as simple as possible, so I will not introduce an additional framework. – Björn Pollex Jun 28 '11 at 21:57
  • I understand that - but _framework_ is a big word for a simple CDI extension (and being extendible is a part of the CDI concept). If you want to avoid dependencies, just use these two classes ([ViewScopedExtension](https://github.com/seam/faces/blob/master/impl/src/main/java/org/jboss/seam/faces/context/ViewScopedExtension.java) [ViewScopedContext](https://github.com/seam/faces/blob/master/impl/src/main/java/org/jboss/seam/faces/context/ViewScopedContext.java)) – Jan Groth Jun 29 '11 at 04:58