3

How can I replace an @ApplicationScoped managed bean with my own copy of it in FacesContext? All I have is an instance of FacesContext (I'm inside JSFUnit).

yegor256
  • 102,010
  • 123
  • 446
  • 597

1 Answers1

4

Application scoped beans are stored in the application map with the managed bean name as key.

So, this should do:

FacesContext.getCurrentInstance().getExternalContext()
    .getApplicationMap().put("managedBeanName", new Bean());

By the way, deeper under the JSF covers up to the Servlet API, the application map is just a mapping of ServletContext attributes. Useful to know when it happens that you've only the ServletContext at your hands. And in the same line, the session map maps to HttpSession attributes and the request map to HttpServletRequest attributes. Use them for session and request scoped beans respectively.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • BalusC you once posted about using attributes / info across redirects. You suggested using the sessionmap and afterwards clearing it with a filter. I think a link to the post might be helpful for some (i really can no longer find that one, you are posting too much §|¦¬). Or at least it seems a lot nicer to clean the HttpSession and fill the request map instead of doing the FacesContext.getCurrentInstance.... – Toskan Apr 26 '11 at 16:12
  • This one maybe? http://stackoverflow.com/questions/4610771/dynamic-chart-generation-pass-object-to-servlet-from-jsf-1-2 Anyway, the real right solution depends on JSF version and functional requirement. – BalusC Apr 26 '11 at 18:54