步形式;客户或者bean都无须依赖对方的直接响应了。
比如,伦敦的一位银行官员使用一种应用程序发布最新的汇率消息。这时,部署在波士顿的一个外部交易bean从消息队列中获取这一消息然后更新数据库中的有关记录。在理想的情况下,消息驱动Bean会把信息传递给处理数据库事务的实体Bean。这样,每一种bean把它不能处理的任务转发从而创建出一种真正的分布式组件结构。
EJB的原理
现在不考虑EJB的类别,以上三种类型组成了EJB对象:本地接口、远程接口和bean的实现。客户程序使用Java命名和目录接口JNDI(Java Naming and Directory Interface)定位bean的本地接口(JNDI)。本地接口随后返回远程接口的实例,同时暴露必要的bean实现方法。客户程序再调用适当的这些方法。程序清单A所示的代码说明了以上过程。
Listing A
First comes the EJB client class—in this case, a very simple stand-alone user interface:
import javax.ejb.*;
import javax.naming.*;
import java.util.*;
import org.shifter.ejb.*;
public class VerySimpleClient
{
public static void main( String[] args ) {
try {
Context ctx = getInitialContex(); VerySimpleHome home = ( VerySimpleHome )ctx.lookup( "simpleton" );
VerySimple ejb = home.create();
ejb.setName( "Fredrick" );
System.out.println( "My name is " + ejb.getName() );
ejb.remove();
} catch (Exception e) {
e.printStackTrace();
} }
public static Context getInitialContext() throws NamingException {
// Retrieve the Context via JNDI lookup
} }
Now, we define the Home and Remote interfaces. The client interacts directly with these classes:
package org.shifter.ejb;
// The home interface import javax.ejb.*; import java.rmi.RemoteException;
public interface VerySimpleHome extends EJBHome {
public VerySimple create() throws CreateException, RemoteException; }
package org.shifter.ejb;
// The remote interface import javax.ejb.*;
import java.rmi.RemoteException;
public interface VerySimple extends EJBObject {
public String getName() throws RemoteException;
public void setName( String n ) throws RemoteException; }
Finally, we have the implementation of the EJB, where all functionality occurs:
package org.shifter.ejb;
import javax.ejb.*;
public class testertwoEJB implements javax
// Called by the create() method of the home interface.
public void ejbCreate() { }
// Called by the remove() method of the home interface.
public void ejbRemove() { }
// Called when the EJB container makes this bean active.
public void ejbActivate() {
// Resource allocation might go here.
}
// Called when the EJB container makes this bean inactive. public void ejbPassivate() {
// Resource clean up might go here. }
// Set the runtime context
public void setSessionContext(SessionContext ctx) { this.ctx = ctx; }
// *****
// The following methods are the only ones visible
// to EJB clients through this bean’s remote interface.
// *****
public String getName() {
return name; }
public void setName( String n ){
name = ( n != null ) ? n : "Igor"; } }
Enterprise JavaBeans入门(3)
时间:2011-01-21
你可能需要根据bean的类型实现其他方法。比方说,假如客户需要定位实体Bean,那么你的本 |