Tim Brückner
Tim Brückner

Reputation: 2099

Why does the @PostConstruct method not get called using BeanManager.getReference() to obtain an instance?

We are currently moving from JSF-ManagedBeans to CDI. Unfortunately we have made excessive use of the EL-Resolver in the past in order to gain static access to session scoped beans managed by JSF.

Since CDI dependency injection is not available everywhere I rewrote the existing static lookup to make use of the BeanManager (Using SEAM-Solder extending BeanManagerAware).

Iterator<Bean<?>> iterator = beans.iterator();
Bean<T> bean = (Bean<T>) iterator.next(); // possible NPE, I know :)

CreationalContext<T> creationalContext = beanManager.createCreationalContext(bean);
T contextual = (T) beanManager.getReference(bean, type, creationalContext);

return contextual;

The code works and returns a container managed instance of the desired bean. BUT: the methods annotated with @PostConstruct do not get called using getReference(). Perhaps you guys know how to do it. Couldn't find anything googling the issue :-/

Best regards!

Upvotes: 0

Views: 951

Answers (1)

BalusC
BalusC

Reputation: 1108802

You should be using Application#evaluateExpressionGet() for this. Not only for CDI beans, but actually also for JSF beans you previously had.

FacesContext context = FacesContext.getCurrentInstance();
Bean bean = (Bean) context.getApplication().evaluateExpressionGet(context, "#{beanName}", Bean.class);
// ...

Much cleaner, however, is to just use CDI's @Inject or JSF's @ManagedProperty instead.

See also:

Upvotes: 3

Related Questions