CDI SessionScoped Bean results in two instances in one session

I have two instances of the SessionScoped CDI bean for the same session. I had the impression that CDI could create one instance, but it created two. I don’t understand how CDI works, or did I find an error?

Here is the bean code:

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;
    }
}

Here is the Facelet code:

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

Here is the result of the deployment and transition to the page:

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

Using GlassFish 3.0.1

+5
source share
2 answers

Ryan, as covener already wrote, the constructor will also be called for each proxy for this bean. This is the standard behavior of all proxy mechanisms that provide not only a proxy interface (for example, material java.lang.reflect.proxy), but also a real proxy class.

, ct . , , . , , @PostConstruct beans .

LieGrue, Strub

+4

, CDI beans - javassist, openwebbeans.

, @PostConstruct, !

+3

All Articles