本地接口(Local Interface)是EJB的特征之一,它的主要目的是提高位于同一EJB容器中的企业bean(enterprise bean)之间相互访问的性能。比如说,一个会话bean要调用某个实体bean中的一些方法,并且这个会话bean和实体bean存在于同一个EJB服务器中,那么使用本地接口速度就会更快并且耗费更少的资源,因为此时会话bean和实体bean在同一个JVM中运行,它们使用的是Java内存reference而不是Java RMI来传递数据。一个enterprise bean是该使用本地接口还是远程接口,可以遵循如下的规则:
●如果一个会话bean的方法要被位于其所在EJB服务器之外的客户端调用,那么这个会话bean要使用远程接口
●如果一个会话bean的方法仅仅被位于同一EJB服务器中的其它bean所调用,那么这个会话bean应该使用本地接口
●实体bean应该使用本地接口
一个接口如何本地化呢?对于Home Interface而言,它现在需要继承EJBLocalHome接口,相应地,对于Bean Interface而言,它需要继承EJBLocalObject接口。除此之外,因为本地接口不再使用RMI来传递数据,因此它的方法不用再抛出RemoteException了。 下面是一个简单使用了本地接口的实体bean的例子:
LocalStock.java:本地Bean Interface
package
local;
import
javax.ejb.EJBLocalObject;
public
interface
LocalStock
extends
EJBLocalObject
...
{ // the public business methods on the Stock bean // these include the accessor methods from the bean // get the ticker. do not allow ticker to be set through the // interface because it is the primary key. public String getTickerSymbol(); // get and set the name public String getName(); public void setName(String name); }
LocalStockHome.java:本地Home Interface
package
local;
import
javax.ejb.CreateException;
import
javax.ejb.EJBLocalHome;
import
javax.ejb.FinderException;
public
interface
LocalStockHome
extends
EJBLocalHome
...
{ // the create method for the Stock bean public LocalStock create(String ticker, String name) throws CreateException; // the find by primary key method for the Stock bean public LocalStock findByPrimaryKey(String ticker) throws FinderException; }
StockBean .java:Bean Class
package
local;
import
javax.ejb.CreateException;
import
javax.ejb.EntityBean;
import
javax.ejb.EntityContext;
public
abstract
class
StockBean
implements
EntityBean
...
{ // keeps the reference to the context private EntityContext _context; // the abstract access methods for persistent fields public abstract String getTickerSymbol(); public abstract void setTickerSymbol(String ticker); public abstract String getName(); public abstract void setName(String name); // standard entity bean methods public String ejbCreate(String ticker, String name) throws CreateException ...{ setTickerSymbol(ticker); setName(name); return null; } public void ejbPostCreate(String ticker, String name) throws CreateException ...{ } public void setEntityContext(EntityContext ctx) ...{ _context = ctx; } public void unsetEntityContext() ...{ _context = null; } public void ejbRemove() ...{ } public void ejbLoad() ...{ } public void ejbStore() ...{ } public void ejbPassivate() ...{ } public void ejbActivate() ...{ } }