在Java EE 7中,這裏有@Named註釋的用途和用途是什麼?即使沒有它,容器應該能夠在運行時發現這個bean,對吧?@命名註釋的目的是什麼
另外,@Singleton呢?如果開發人員不需要在應用程序中創建多個實例,那麼在這裏不需要使用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,當我通過1.單擊增量型的()或incrementB(),neighter增量值停留在1
2)如果我刪除@Named註釋,它會報告一個空指針異常。
我正在學習Java EE,不太明白這種行爲。
EDIT(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>
〜
一旦@Singleton被移除,計數器不起作用的確切原因是什麼?計數器的值保持在1,不增加。 – marlon 2014-09-27 17:27:37
我認爲這不是價值保持不變,而是每次訪問您的webapp時都會得到一個新實例。不幸的是,我無法看出這個班級在什麼情況下使用。 – 2014-09-27 17:44:30
請看它是如何使用的。很簡單。這是一個演示單例會話bean概念的簡單演示。你的意思是每次我點擊「增量」,我得到一個新的實例?但默認值是1,即使我只點擊一次,新實例的值應該是2? – marlon 2014-09-28 02:27:29