0

A long time ago I had a very similar question: "Access SessionScoped object from stateless EJB", see here, and found a very nice answer here. But time goes on and I start to work with @ViewScoped beans and run into the same problem. How can I simulate such a view to access it from my stateless EJB? I did check for something similar as BoundSessionContext. I did find some candidates for request scoped or conversation scope, but nothing for the view scope.

Can someone help me again?

My current environment is Java 17 and Wildfly 26.1.2.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Martin Metz
  • 308
  • 1
  • 3
  • 13

1 Answers1

2

Nope. That's not possible.

The JSF View Scope is tied to the JSF View State. The JSF View State is in turn tied to the Faces Context. So you can only obtain it via the FacesContext. And in a backend class such as EJB you should absolutely not have any frontend specific dependencies such as FacesContext as that violates the Law of Demeter. See also why shouldn't entity bean be managed by JSF framework?

You need to salvage this other way. If you want to pass data from the frontend to the backend, then simply pass them as method arguments.

@Named
public class YourBackingBean {

    @Inject
    private YourServiceBean yourServiceBean;

    public void someActionMethod() {
        // ...
        yourServiceBean.someServiceMethod(theseArguments);
    }
}

Or if you want to pass data from the backend to the frontend, then simply pass them as method return value.

@Named
public class YourBackingBean {

    @Inject
    private YourServiceBean yourServiceBean;

    public void someActionMethod() {
        SomeObject thisResult = yourServiceBean.someServiceMethod();
        // ...
    }
}

Or if the EJB method is asynchronous, then simply pass the data via a CDI event.

@Stateless
public class YourServiceBean {

    @Inject
    private BeanManager beanManager;

    @Asynchronous
    public void someAsyncServiceMethod() {
        // ...
        beanManager.getEvent().select().fire(thisResult);
    }
}
@Named
public class YourBackingBean {

    public void observerMethod(@Observes SomeObject thisResult) {
        // ...
    }
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Thanks for the fast answer. That's disapointing, after it was mostly easy for the session scope. Unfortunately, I do not need to communicate with my UI, but re-use some validation code, not only be done in UI context but also e. g. at startup of the application if all configurations are still valid. But: Yes, I have to find another solution. Maybe POJO, accessed once from view scope CDI bean, once directly. Anyhow, I'm still in research of how and where to use the view scope at all. But after first positive results, there are a lot of details, reducing the posibilites a lot! – Martin Metz Oct 24 '22 at 15:14