技术开发 频道

将EJB 2.x的应用程序迁移到EJB 3.0

{$PageTitle=将EJB 2.x的应用程序迁移到EJB 3.0{1}}
IT168 技术新闻】 
    这篇文章假设你已经熟悉了EJB,Java 5和对象关系映射的特征和概念。

    EJB 2.1到EJB 3.0:发生了什么变化? 

    Session bean 
    在EJB 2.1和更早的规范中,两个接口-主接口和本地接口,或者远程接口,业务接口-bean的执行类要求每一个Session bean。主接口要求扩展到EJBHome或者EJBLocalHome接口并且声明生命周期方法例如create(). 本地或者远程,业务
接口要求扩展EJBObject 或者EJBLocalObject接口并且声明业务方法。bean执行类本身是一个EnterpriseBean 类型,就session beans而言,扩展了SessionBean 子接口,在bean类中必须提供Callback方法以至于当合适的周期事件发生时容器能够触发他们。另外,bean的关键元素包括事务和安全定义和是否是正式的还是非正式的在相关的部署描述符中都被定义了。 

    Listing 1 阐述了使用EJB 2.1规范定义的stateful session bean的例子 

    Listing 1 EJB 2.1-一个基于银行服务stateful session bean
public interface BankingService extends EJBObject { public void deposit(int accountId, float amount) throws RemoteException; public void withdraw(int accountId, float amount)throws RemoteException; public float getBalance(int accountId) throws RemoteException; public void doServiceLogout() throws RemoteException; } public interface BankingServiceHome extends EJBHome { public BankingService create() throws CreateException, RemoteException; } public class BankingServiceEJB implements SessionBean { public void deposit(int accountId, float amount) throws RemoteException { //Business logic to deposit the specified amount and update the balance } public void withdraw(int accountId, float amount)throws RemoteException { //Business logic to withdraw the desired amount and update the balance } public float getBalance(int accountId) throws RemoteException { //Business logic to get the current balance } public void doServiceLogout() throws RemoteException { //Service completion and logout logic } public void ejbCreate(){} public void ejbActivate(){} public void ejbPassivate(){} public void ejbRemove(){} public void setSessionContext(SessionContext context){} }

    在EJB 3.0规范中,一个session bean 仅需要一个业务接口和bean的执行类,主接口已经被移除了。业务接口是一个规则的Java接口,有时也叫POJI,或者简单原始的Java接口,业务接口不需要扩展EJBObject和EJBLocalObject 接口,相反
,如果有需要,它被定义在代表业务域模型的接口。
 
    bean执行类是一个规则的Java类,有时也叫POJO,或者简单原始的Java对象,它没有实施EnterpriseBean 类型。在部署描述符中的声明和配置被定义为Java代码。另外,对于大多数配置来说,默认值是需要提供的。在新的规范下,能够不
用ejb-jar.xml来部署session beans。
 
    Listing 2 阐述了使用EJB 3.0规范定义的stateful session bean的例子 

    Listing 2 EJB 3.0-一个基于银行服务stateful session bean
@Remote public interface BankingService { public void deposit(int accountId, float amount); public void withdraw(int accountId, float amount); public float getBalance(int accountId); publlic void doServiceLogout(); } @Stateful public class BankingServiceBean implements BankingService { public void deposit(int accountId, float amount) { //Business logic to deposit the specified amount and update the balance } public void withdraw(int accountId, float amount) { //Business logic to withdraw the desired amount and update the balance } public float getBalance(int accountId) { //Business logic to get the current balance } @Remove public void doServiceLogout () { //Service completion and logout logic } }

0
相关文章