單例會話 Bean(Singleton Session Bean)以 @Singleton 定義,保證在應用程式 JVM 內僅實例化一次。適用於快取、共用配置等跨元件共享狀態場景。
@Singleton
public class PropertiesBean {
private Properties props;
@PostConstruct public void initialize() { props = ...; }
public String getProperty(String name) { ... }
}
客戶端以 @EJB 注入:
@EJB private PropertiesBean propsBean;
String msg = propsBean.getProperty("hello.message");
容器確保所有呼叫導向同一實例。預設執行緒安全(阻塞並發呼叫),亦提供其他並發選項以提高效率。