在EJB3中,所有的服務(wù)對象管理都是POJOS(e.g., session beans)或者是輕量級組件(e.g., message driven beans).
簡單的看下各種BEAN:
1:Stateless Session Beans(EJB3中已經(jīng)不再有HOME接口了)
Define the session bean interface
要定議一SESSION BEAN,首先必須定義一服務(wù)接口包含它所有的業(yè)務(wù)邏輯方法(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可以繼承多個接口,每個接口對應(yīng)不同類型的客戶端,默認的接口是“LOCAL”,也就是運行在EJB3窗口的同一個JVM中,比如說,以上的BENAS和JSP頁面都運行于同一個JBOSS JVM中。也是繼承ROMOTE接口,遠程客戶通過遠程調(diào)用此接口,此接口一般除了LOCAL中的方法外,不有些別的方法(相對LOCAL而言),比如對服務(wù)端的說明。如下 :

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

public String getServerInfo ();

}

The session bean client
一旦此BEAN部署到了EJB3的窗口,也就已經(jīng)在服務(wù)器中的JNDI注冊中已經(jīng)注冊(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中對此接口的類名的引用來實現(xiàn)對其方法的引用。客戶端代碼(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);
}
注:應(yīng)盡量避免使用遠程接口(效率,花費...)
在繼承實現(xiàn)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
在接口中分別指定,這樣就不用在繼承實現(xiàn)類中再指定了,如:
@Remote
public interface RemoteCalculator


{ //
}
總結(jié):本節(jié)主要學(xué)習(xí)了如何開發(fā)sessionless bean ,有時間繼續(xù)討論sessionful bean.
參考:www.jboss.org相關(guān)文獻。