如何将辅助类注释为在 JSF 中可见? [英] How to annotate helper class to be visible inside JSF?

查看:26
本文介绍了如何将辅助类注释为在 JSF 中可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个辅助类,它既不是 stateful managed bean,也不是 stateless EJB,也没有 entity 通过 JPAHibernate 映射到表.它只是一个静态方法的集合,可以做一些简单的事情,比如返回日期格式等.

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.

鉴于为了使 Java 类在 JSF 中可见,该类必须以容器分配为对 JSF 可见的方式进行注释,是否有一种方法可以注释与任何不匹配的辅助类标准的 JSF 可见类别,以便它变得可见?当然,另一种方法是在托管 bean 中有一个管道方法,它将调用从 JSF 传递到帮助程序类,但如果我可以直接从 JSF 调用它,我宁愿不要弄乱我的托管 bean.我知道使用来自 JSF 的无状态 EJB 执行此操作将被视为反模式,但我希望使用的类中的方法都非常简单且非事务性.

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.

推荐答案

将您的班级标记为 @ApplicationScoped.确保它有一个公共的无参数构造函数,并且这个类没有状态并且它的方法是线程安全的.

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.

例如

托管 bean(纯 JSF)

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 版本

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

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

查看

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

这篇关于如何将辅助类注释为在 JSF 中可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆