@SessionScoped
public class SessionScopedClass implements Serializable {
//This class gets constructed once per session, and is shared among all CDI-managed classes within that session. Notice that it implements Serializable, since the instance will get put on the session.
@Inject
public SessionScopedClass(SomeDependency someDependency) {
doSomethingWith(someDependency);
}
public SessionScopedClass() {
//Note that it is required that a session scoped class have a public no-args constructor
}
}
Classes annotated with @SessionScoped will be created once per session, and two objects within the same session will share the same instance of the session scoped class.
It is important to notice that the session scoped class should implement Serializable. This requirement exists because the bean will be stored in the servlet container's session for that particular session scoped instance. In general, any object being put into the session needs to be serializable for two reasons: First, sessions may be persisted to disk after a certain amount of inactivity to save memory. This is know as session passivation, and it requires serialization. The second reason is that in high-availability clusters, session replication is often used in order to allow any server in the cluster to service a request for a given session. This also generally requires serialization.
Much like request scoped and application scoped, session scoped classes must have a public no-args constructor.