Reputation: 76778
The way I see it, there are three ways to get a reference to another bean:
@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.@ManagedProperty
seems to be ideal, apart from the fact that I have to introduce a public setter for that to work, which hurts encapsulation.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
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