Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get managed bean reference in another managed bean

I try to get instance of managed bean in another managed bean thanks to this BalusC post : here

With findBean method, it's great, I retrieve my bean but with ManagedProperty I can not get my bean.

My bean to inject is this one :

@ManagedBean(name="locale")
@SessionScoped
public class LocaleBean {

   private String locale;

   public String getLocale() {              
        return locale;
   }

   public void setLocale(String locale) {
        FacesContext.getCurrentInstance().getViewRoot().setLocale(new Locale(locale));      
        this.locale = locale;
   }

}

So when I call LocaleBean locale = findBean("locale"); in my login bean it's work but :

@ManagedProperty("#{locale}") // OR localeBean, LocaleBean...
private LocaleBean locale;

doesn't work...

com.sun.faces.mgbean.ManagedBeanCreationException: Impossible de créer le bean géré «login». Les problèmes suivants ont été détectés : - La propriété «locale» du bean géré «login» n’existe pas.

Why please ?

like image 951
Olivier J. Avatar asked Dec 27 '12 15:12

Olivier J.


2 Answers

you should write getter/setter for bean which is annotated @ManagedProperty

like image 142
Kerem Can Kurtay Avatar answered Sep 20 '22 20:09

Kerem Can Kurtay


I see that your LocaleBean is session scoped. Instead of the @ManagedProperty annotation and the getters/setters, you can reference another session scoped managed bean directly from the code using the getSessionMap method of the servlet context:

LocaleBean locale = (LocaleBean) FacesContext.getCurrentInstance()
                    .getExternalContext().getSessionMap().get("locale");
like image 28
Donato Szilagyi Avatar answered Sep 22 '22 20:09

Donato Szilagyi