0

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!

Tim Brückner
  • 1,928
  • 2
  • 16
  • 27

1 Answers1

3

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:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for your suggestion @BalusC, I really appreciate your help. We would use `@Inject` but we need access within classes that are not pulled up by the container (ResourceResolver). I've tried using `evaluateExpressionGet()` and I do receive an instance of the managed bean, but the method annotated with `@PostConstruct`does not get called, too. When I include the bean within a facelet like `#{myBean.someValue}` the `@PostConstruct` method gets called. Guess I'll have to rollback to JSF's `@ManagedBean` annotations, so we can still use the constructor to initialize the beans. Thanks anyways! – Tim Brückner Feb 02 '12 at 11:08