gpt4 book ai didi

jakarta-ee - @Named 注释的目的是什么

转载 作者:行者123 更新时间:2023-12-03 09:23:33 26 4
gpt4 key购买 nike

在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>

最佳答案

如果没有 @Named,Bean 将无法在 JSF 的 EL 中使用。

如果没有@Singleton,bean 就是一个普通的 CDI ManagedBean。每个作用域都有一个托管 Bean,而不是只有一个单独的实例来计数。当您删除@Singleton时,最好添加@SessionScoped或@ApplicationScoped,具体取决于您是要对每个 session 进行计数还是对所有 session 进行计数(就像@Singleton一样)。

关于jakarta-ee - @Named 注释的目的是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26071779/

26 4 0