現代 EJB 3.x 已大幅簡化(無需 Home/Remote 介面,使用注解),但理解傳統流程有助於維護舊系統。
@Remote
public interface MyEJB {
String sayHello() throws RemoteException;
}
@RemoteHome
public interface MyEJBHome extends EJBHome {
MyEJB create() throws RemoteException, CreateException;
}
@Stateless
public class MyEJBBean implements SessionBean {
public void ejbCreate() throws CreateException {}
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void setSessionContext(SessionContext ctx) {}
public String sayHello() { return "Hello EJB"; }
}
ejb-jar.xml<ejb-jar>
<enterprise-beans>
<session>
<ejb-name>helloEjb</ejb-name>
<home>com.jsper.ejb.MyEJBHome</home>
<remote>com.jsper.ejb.MyEJB</remote>
<ejb-class>com.jsper.ejb.MyEJBBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
</enterprise-beans>
</ejb-jar>
META-INF/ejb-jar.xml 打成 JARappc、JBoss ejbc)生成存根/骨架Context ctx = new InitialContext();
MyEJBHome home = (MyEJBHome) ctx.lookup("hello");
MyEJB ejb = home.create();
ejb.sayHello();
需配置 JNDI 環境屬性(Provider URL、初始工廠、安全憑證):
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
env.put(Context.PROVIDER_URL, "t3://localhost:7001");
env.put(Context.SECURITY_PRINCIPAL, "user");
env.put(Context.SECURITY_CREDENTIALS, "pass");
Context ctx = new InitialContext(env);
MyEJBHome home = (MyEJBHome) ctx.lookup("hello");
@Remote 或 @Local 標註業務介面@Stateless/@Stateful/@Singleton 標註@EJB MyEJB ejb;@Local 介面(同一應用內調用),避免遠程序列化開銷@Stateless) 適合高併發業務邏輯@Stateful) 僅用於會話級狀態維護REQUIRED,按業務需要調整