我正在使用J2EE和Glassfish开始我的第一步。我正在试验the examples from the J2EE 6 tutorial,更具体地说是“hello1”。
我有以下bean:
@ManagedBean(eager=true)
@ApplicationScoped
public class Hello {
private String name;
private Logger log = Logger.getLogger(Hello.class.getName());
public Hello() {
log.info("Ctor: Hello has been created" + this.getClass().getName());
}
@PostConstruct
public void postConstruct() {
log.info("postConstruct() " + this.getClass().getName());
}
public String getName() {
return name;
}
public void setName(String user_name) {
this.name = user_name;
}
}
以下XHTML:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Facelets Hello Greeting</title>
</h:head>
<h:body>
<h:form>
<h:graphicImage url="duke.waving.gif"/>
<h2>Hello, my name is Duke. What's yours?</h2>
<h:inputText id="username"
value="#{hello.name}"
required="true"
requiredMessage="A name is required."
maxlength="25">
</h:inputText>
<p></p>
<h:commandButton id="submit" value="Submit" action="response">
</h:commandButton>
<h:commandButton id="reset" value="Reset" type="reset">
</h:commandButton>
</h:form>
</h:body>
</html>
应用程序正在运行,但显然创建了bean的多个实例:
2014-03-27T11:23:44.077+0100|Information: Ctor: Hello has been createdhello1.Hello
2014-03-27T11:23:44.077+0100|Information: postConstruct() hello1.Hello
2014-03-27T11:23:46.713+0100|Information: Ctor: Hello has been createdhello1.Hello
2014-03-27T11:23:46.713+0100|Information: postConstruct() hello1.Hello
2014-03-27T11:23:49.112+0100|Information: Ctor: Hello has been createdhello1.Hello
2014-03-27T11:23:49.112+0100|Information: postConstruct() hello1.Hello
起初我认为创建了代理,这就是我在日志中添加this.getClass().getName()
的原因,但事实并非如此。此外,hello.name不在实例之间共享。
从我可以阅读的所有文档和示例中,@ApplicationScoped
应该在应用程序级别创建一个单例。此外,eager=trye
无法按预期工作,因为在应用程序启动时未创建任何实例。我做错了什么?
答案 0 :(得分:1)
发出问题一分钟后,我发现了问题。正如Adarsh所怀疑的那样,我正在导入javax.enterprise.context.ApplicationScoped
而不是javax.faces.bean.ApplicationScoped