@Named注释的目的是什么?

时间:2014-09-27 05:57:03

标签: java-ee annotations cdi

在Java EE 7中,@ Named注释的用途和用途是什么?即使没有它,容器也应该能够在运行时发现这个bean,对吗?

另外,@ Singleton呢?如果开发人员不需要在应用程序中创建多个实例,则不需要在这里使用单例,对吧?

@Singleton
@Named
public class Counter {

private int a = 1;
private int b = 1;

public void incrementA() {
    a++;
}

public void incrementB() {
    b++;
}

public int getA() {
    return a;
}

public int getB() {
    return b;
}
}

我做了两次测试:

1)如果我删除@Singleton,当我单击incrementA()或incrementB()时,更高的增量为1.该值保持为1。

2)如果删除@Named注释,它会报告空指针异常。

我正在学习Java EE并且不太了解这种行为     编辑(如何使用bean):

<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<body>
    <ui:composition template="/template.xhtml">
            <ui:define name="title">
      Helloworld EJB 3.1 Singleton Quickstart
            </ui:define>
            <ui:define name="body">
     <p>
        This example demonstrates a singleton session bean that maintains state for 2 variables: <code>a</code> and <code>b</code>.
     </p>
                    <p>
        A counter is incremented when you click on the
                            link to the variable name. If you close and restart your browser, or
                            if you have multiple browsers, you can see that the counter always
                            increments the last value. These values are maintained until you
                            restart the application. To test the singleton bean, click on either
                            "Increment" button below.
     </p>
               <table>
        <tr>
           <h:form>
              <td><b>Counter A</b></td><td><h:commandButton value="Increment" action="#{counter.incrementA}" /></td><td>#{counter.a}</td>
           </h:form>
        </tr>
        <tr>
           <h:form>
              <td><b>Counter B</b></td><td><h:commandButton value="Increment" action="#{counter.incrementB}" /></td><td>#{counter.b}</td>
           </h:form>
        </tr>
     </table>
            </ui:define>
    </ui:composition>

3 个答案:

答案 0 :(得分:2)

如果没有@Named,Bean将不能用于JSF中的EL。

如果没有@Singleton,bean就是普通的CDI ManagedBean。 而不是只有一个单例实例,每个范围有一个受管Bean。当您删除@Singleton时,最好添加@SessionScoped或@ApplicationScoped,具体取决于您是要计算每个会话还是所有会话(就像使用@Singleton一样)。

答案 1 :(得分:1)

单例注释使EJB在整个EE应用程序中是唯一的(在线程和请求之间共享),与其他类型的EJB(如会话Bean)完全不同,它们在会话中有生命,在该会话中维护内部州。注意:单个元素在高并发环境中使用时会影响性能。

@Named如何,我不使用Java EE7,但我认为在JSF中更多地使用不同的名称来称为ManagedBean(在新版Java EE中不推荐使用托管bean)。简单地说,如果你创建一个名为MyBean的bean,你可以在JSF页面中将该bean称为myBean,如果你想使用另一个名称你可以使用:

@Named( “myNewBeanName”)

您可以在JSF页面中使用myNewBeanName。

答案 2 :(得分:1)

使用CDI,您需要一对bean的范围和限定符。 Singleton是范围的示例,Named是限定符的示例。限定符是查找bean时如何派生的。当在表示层中组合以在视图中或类似地引用它时,专门使用命名。 Singleton允许它作为单个实例公开。请注意,Singleton来自AtInject规范,并且不被视为bean定义,它不是正常范围。以CDI为中心的方法是使用ApplicationScoped。无论哪种方式,都会创建一个类的实例。

限定符是可选的,因此如果您想在UI中使用它,则只需要命名。

相关问题