tags:

views:

1117

answers:

2

Am I right in thinking that this may not be the best idea:

private static Application app = FacesContext.getCurrentInstance()
        .getApplication();

... or any other call to FacesContext.getCurrentInstance() when you can't be sure that the current thread of execution is due to a servlet request?

The way I understand it, FacesContext.getCurrentInstance() works by assigning the current faces context to the thread (e.g. ThreadLocal variable). The above will probably usually work in a class like a JSF backing bean or JSF component class, since the thread of execution that happens to load the class and instantiates the class members (static variables) is usually going to be a FacesServlet request. But I still don't think it's a good idea to count on it.

Agree or disagree? Ideas? Thanks.

A: 

Using FacesContext.getCurrentInstance() during initialization may or may not be a good idea depending upon the context.

I can't imagine a scenario where assigning it to a static var would ever be a good idea, though.

jsight
A: 

This doesn't look like something you'd really want to do.

If you must get a static reference to the application, initializing it through an ApplicationFactory would probably be a better approach:

public final class CustomApplicationFactory extends ApplicationFactory {
  private static volatile Application APPLICATION;
  private final ApplicationFactory decorated;

  public CustomApplicationFactory(ApplicationFactory decorated) {
    this.decorated = decorated;
  }

  @Override public Application getApplication() {
    APPLICATION = decorated.getApplication();
    return APPLICATION;
  }

  @Override public void setApplication(Application application) {
    APPLICATION = application;
    decorated.setApplication(application);
  }

  public static Application getApp() {
    return APPLICATION;
  }
}

This would be registered in your faces-config.xml. This demo class is vulnerable to ClassLoader related bugs if you don't keep it isolated to a single app.

There's probably a better way of doing whatever it is you're trying to do.

McDowell