How to annotate helper class to be visible inside

2019-08-23 06:33发布

问题:

I have a helper class, which is neither a stateful managed bean, nor a stateless EJB, nor an entity mapped to a table via JPA or Hibernate. It is simply a collection of static methods that do simple things like return date formats and similar.

Given that, in order for a Java class to be visible inside a JSF, that class must be annotated in a way that the container assigns as visible to JSFs, is there a way to annotate a helper class that does not match any of the standard JSF visible categories so that it becomes visible? An alternative, of course, is to have a conduit method in the managed bean that passes the call from the JSF to the helper class but I prefer not to clutter my managed bean if I can call it directly from the JSF. I understand that doing this with a stateless EJB from a JSF would be considered an anti-pattern but the methods in the class I wish to use are all very simple and non-transactional.

回答1:

Mark your class as @ApplicationScoped. Make sure it has a public no-arg constructor and that this class doesn't have state and its methods are thread safe.

E.g.

Managed bean (pure JSF)

//this is important
import javax.faces.bean.ApplicationScoped;

@ManagedBean
@ApplicationScoped
public class Utility {
    public static String foo(String another) {
        return "hello " + another;
    }
}

CDI version

//this is important
import javax.enterprise.context.ApplicationScoped;

@Named
@ApplicationScoped
public class Utility {
    public static String foo(String another) {
        return "hello " + another;
    }
}

View

<h:outputText value="#{utility.foo('amphibient')}" />