A session bean needs to interact with the container (get security info, check rollbacks, get a reference to its own EJB object). How does the bean access these container-provided services?
SessionContext is the EJB context specific to session beans. It extends EJBContext and provides getEJBObject() and getEJBLocalObject() methods, which beans use to get a reference to themselves (never use this keyword in EJB).
- setSessionContext(): Container calls this to inject the context
- getEJBObject(): Returns reference to the bean’s EJB object (remote)
- getEJBLocalObject(): Returns reference to the bean’s local EJB object
- Why not
this?:thisis the raw bean; clients call via EJB object proxy - Usage: Pass self-reference to other beans via
getEJBObject()
- Extends EJBContext: Inherits
getCallerPrincipal(),setRollbackOnly(), etc. - Injected by container: Via
setSessionContext()callback getEJBObject(): For remote interfacesgetEJBLocalObject(): For local interfaces- Never use
this: Bean must use EJB object for self-reference
- Built from: EJB Context — SessionContext extends EJBContext
- Related: Session Bean — SessionContext is for session beans
- Contrasts with: Entity Context — entity beans have different context
- Related: Why Bean Doesn't Implement Interface —
thisdanger - Builds into: Business Interface Pattern — context used in pattern
thisdanger: Passingthisbypasses container services- Null check: Context may be null before
setSessionContext()called - Runtime only: Context not available during
new(only after container injects) - Method restrictions: Can’t call
getEJBObject()inejbCreate()(EJB object not associated yet)