The way I see it, there are three ways to get a reference to another bean:
- 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. - 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. 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.