对于同一个 session ,我有两个 SessionScoped CDI bean 实例。我的印象是 CDI 会为我生成一个实例,但它生成了两个。我是否误解了 CDI 的工作原理,还是我发现了一个错误?
这是bean代码:
package org.mycompany.myproject.session;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.http.HttpSession;
@Named @SessionScoped public class MyBean implements Serializable {
private String myField = null;
public MyBean() {
System.out.println("MyBean constructor called");
FacesContext fc = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);
String sessionId = session.getId();
System.out.println("Session ID: " + sessionId);
}
public String getMyField() {
return myField;
}
public void setMyField(String myField) {
this.myField = myField;
}
}
这是 Facelet 代码:
<?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"
xmlns:f="http://java.sun.com/jsf/core">
<f:view contentType="text/html" encoding="UTF-8">
<h:head>
<title>Test</title>
</h:head>
<h:body>
<h:form id="form">
<h:inputText value="#{myBean.myField}"/>
<h:commandButton value="Submit"/>
</h:form>
</h:body>
</f:view>
</html>
这是部署和导航到页面的输出:
INFO: Loading application org.mycompany_myproject_war_1.0-SNAPSHOT at /myproject
INFO: org.mycompany_myproject_war_1.0-SNAPSHOT was successfully deployed in 8,237 milliseconds.
INFO: MyBean constructor called
INFO: Session ID: 175355b0e10fe1d0778238bf4634
INFO: MyBean constructor called
INFO: Session ID: 175355b0e10fe1d0778238bf4634
使用 GlassFish 3.0.1
最佳答案
Ryan,正如 covener 已经写的那样,构造函数也将被该 bean 的每个代理调用。这是所有代理机制的标准行为,它不仅提供接口(interface)代理(如 java.lang.reflect.proxy 的东西),而且提供真正的类代理。
还想象一下,每次序列化都会调用 ct 。所以如果你在一个负载均衡的集群上工作,你会看到很多次。因此,请在一般情况下对 bean 使用 @PostConstruct。
列格鲁,
串
关于jsf - CDI SessionScoped Bean 在同一 session 中产生两个实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4594848/