1、下載例子源程序
所有例子的源代碼可以直接從 www.jboss.org進(jìn)行下載。下載完后放在一個(gè)目錄下。下載網(wǎng)址:http://www.jboss.org/docs/manual/files/documentation-example.zip
1.1 建立 BEAN
此節(jié)主要是建立一個(gè)簡(jiǎn)單的EJB,可以查看代碼,這個(gè)“Interest”例子,是一個(gè)簡(jiǎn)單無(wú)狀態(tài)的會(huì)話EJB。它的目的是根據(jù)說(shuō)明的利息率,來(lái)對(duì)借的所有錢計(jì)算利息。實(shí)際上在整個(gè)包代碼中只有一行功能。
1.2 回顧EJBs
在我們查看代碼之前,我們先對(duì)EJB進(jìn)行復(fù)習(xí)一下。在EJB最小類型,也必須有三個(gè)類:remote interface, home interface和bean實(shí)現(xiàn)類。
remote interface是會(huì)把EJB中方法提供給外邊世界,讓外邊的代碼來(lái)進(jìn)行調(diào)用,在這個(gè)例子中類名稱是org.jboss.interest.Interrest。
home interface是治理remote interface類的類。包括建立、刪除等操作。在這個(gè)例子中類名稱是org.jboss.interest.InterrestHome。
bean實(shí)現(xiàn)類提供home interface和remote interface所有方法的實(shí)現(xiàn)。在這個(gè)例子中類名稱是org.jboss.interest.InterrestBean。
當(dāng)然一個(gè)Bean可能還包括其他類,甚至其他包。但是必須有此三個(gè)類,其他類是在此三個(gè)類之上建立的。所有類被打包進(jìn)一個(gè)JAR文件,此文件是用一個(gè)目錄結(jié)構(gòu)來(lái)反映出包的層次關(guān)系。在此例子中所有類都打包在org.jboss.interest包中,所以他們需要在目錄org/jboss/interest/下。
在包含所有類的jar文件建立之前,必須有一個(gè)META-INF目錄。此目錄存放了部署描述符(通常叫“ejb-jar.
xml”),和可選的其他XML文件。這些文件告訴服務(wù)器關(guān)于應(yīng)用明確服務(wù)信息。對(duì)于JBoss 來(lái)講,文件名必須叫“jboss.xml”。
創(chuàng)建jar文件后部署到JBoss Server上。在客戶端你需要一個(gè)jndi.
PRoperties文件,此文件告訴你的客戶端程序從哪里初始化查找JNDI 命名服務(wù)。從這個(gè)服務(wù),客戶端將查找到Interest bean,并且返回bean的home interface。home interface用來(lái)得到bean的一個(gè)remote interface。它可以用遠(yuǎn)程接口來(lái)訪問(wèn)bean提供的商業(yè)方法。
1.3 EJB類
我們需要三個(gè)類:remote interface, home interface 和bean實(shí)現(xiàn)類。remote interface遠(yuǎn)程接口類,文件名Interest.
java。代碼如下:
package org.jboss.docs.interest;
import javax.ejb.EJBObject;
import java.rmi.RemoteException;
/**
This interface defines the `Remote' interface for the `Interest' EJB. Its
single method is the only method eXPosed to the outside world. The class
InterestBean implements the method.
*/
public interface Interest extends EJBObject
{
/** Calulates the compound interest on the sum `principle', with interest rate per period `rate' over `periods' time periods. This method also prints a message to standard output; this is picked up by the EJB server and logged. In this way we can demonstrate that the method is actually being executed on the server, rather than the client. */
public double calculateCompoundInterest(double principle, double rate, double periods) throws RemoteException;
}
遠(yuǎn)程接口只有一個(gè)商業(yè)方法calculateCompoundInterest。Home interface 文件名InterestHome.java。代碼如下:
package org.jboss.docs.interest;
import java.io.Serializable;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
/**
This interface defines the 'home' interface for the 'Interest' EJB.
*/
public interface InterestHome extends EJBHome
{
/** Creates an instance of the `InterestBean' class on the server, and returns a remote reference to an Interest interface on the client. */