JAVA

人生若只如初见,何事秋风悲画扇。

  语源科技BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  50 随笔 :: 25 文章 :: 157 评论 :: 0 Trackbacks

在EJB3中,所有的服务对象管理都是POJOS(e.g., session beans)或者是轻量级组件(e.g., message driven beans).

简单的看下各种BEAN:

1:Stateless Session Beans(EJB3中已经不再有HOME接口了)

Define the session bean interface

要定议一SESSION BEAN,首先必须定义一服务接口包含它所有的业务逻辑方法(define the service interface containing all its business methods.)SESSION BEAN的接口没有注释,客户通过EJB3的窗口来获取此对象接口。

public interface Calculator 
{ 
     
public double calculate (int start, int end, double growthrate, double saving); 
}
 

The session bean implementation

定义好接口好后,就是提供对此接口的继承了,此继承是一个简单的POJO,EJB3的窗口自动实例化管理此POJO。由@Stateless来申明类型。注意此类名后面一定得有Bean,如CalculatorBean


@Stateless
public class CalculatorBean 
               
implements Calculator, RemoteCalculator {

  
public double calculate (int start, int end, 
                    
double growthrate, double saving) {
    
double tmp = Math.pow(1. + growthrate / 12., 
                          
12. * (end - start) + 1);
    
return saving * 12. * (tmp - 1) / growthrate;
  }


}
 


Remote and local interface

一个SESSION BEAN可以继承多个接口,每个接口对应不同类型的客户端,默认的接口是“LOCAL”,也就是运行在EJB3窗口的同一个JVM中,比如说,以上的BENAS和JSP页面都运行于同一个JBOSS JVM中。也是继承ROMOTE接口,远程客户通过远程调用此接口,此接口一般除了LOCAL中的方法外,不有些别的方法(相对LOCAL而言),比如对服务端的说明。如下 :

public interface RemoteCalculator {
  
public double calculate (int start, int end, double growthrate, double saving); 

 
public String getServerInfo (); 

}

 



The session bean client

一旦此BEAN部署到了EJB3的窗口,也就已经在服务器中的JNDI注册中已经注册(Once the session bean is deployed into the EJB 3.0 container, a stub object is created and it is registered in the server's JDNI registry.)。客户端可以通过在JNDI中对此接口的类名的引用来实现对其方法的引用。客户端代码(JSP中哦):

private Calculator cal = null;

public void jspInit () {
    
try {
      InitialContext ctx 
= new InitialContext();
      cal 
= (Calculator) ctx.lookup(
                  Calculator.
class.getName());
    }
 catch (Exception e) {
      e.printStackTrace ();
    }

}


//  

public void service (Request req, Response rep) {
    
//  
    double res = cal.calculate(start, end, growthrate, saving);
}

注:应尽量避免使用远程接口(效率,花费...)

在继承实现BEAN的类中可以通过@Local and @Remote 的注释来指定此BEAN的接口类型。如:

@Stateless 
@Local(
{Calculator.class}) 
@Remote (
{RemoteCalculator.class}) 
public class CalculatorBean implements Calculator, RemoteCalculator 
{
  
public double calculate (int start, int end, double growthrate, double saving) 
  
{ 
    
double tmp = Math.pow(1. + growthrate / 12., 12. * (end - start) + 1); 
    
return saving * 12. * (tmp - 1) / growthrate; 
  }


  
public String getServerInfo () 
  
{
    
return "This is the JBoss EJB 3.0 TrailBlazer"; 
  }

}
 


也可以通过@Local and @Remote在接口中分别指定,这样就不用在继承实现类中再指定了,如:

@Remote 
public interface RemoteCalculator 
{ //   } 


总结:本节主要学习了如何开发sessionless bean ,有时间继续讨论sessionful bean.

参考:www.jboss.org相关文献。

posted on 2006-01-24 00:47 Jkallen 阅读(576) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航: