承接上篇文章,我們已經使用過無狀態會話 Bean。現在詳細分析上一個範例程式碼。若尚未閱讀前文,請先參考 《一步步學 EJB 3.0 (二):初探企業 EJB 模組開發》。
@Remote
public interface HelloRemote {
void sayHello(String str);
}
使用 @Remote 註解標記此介面為遠端介面。
@Stateless(mappedName="myejb/hello")
@Remote(HelloRemote.class)
public class HelloBean implements HelloRemote {
public void sayHello(String str) {
System.out.println("Hello " + str);
}
}
關鍵註解說明:
@Stateless:標記為無狀態會話 Bean,mappedName 指定 JNDI 名稱。@Remote:宣告此 Bean 實作的遠端介面。public class Main {
public static void main(String[] args) throws Exception {
Context ctx = new InitialContext();
HelloRemote hw = (HelloRemote) ctx.lookup("myejb/hello");
hw.sayHello(" Beniao!");
}
}
客戶端透過 JNDI 查找 mappedName 取得 Bean 實例並呼叫方法。
以購物車為例展示有狀態會話 Bean。
@Remote
public interface ShoppingCartRemote {
void addItem(String item, int quantity);
void removeItem(String item, String quantity);
Map<String, Integer> getItems();
void clearItems();
}
@Stateful(mappedName="ejb/ShoppingCart")
public class ShoppingCartBean implements ShoppingCartRemote {
private HashMap<String, Integer> items = new HashMap<String, Integer>();
public void addItem(String item, int quantity) {
Integer orderQuantity = items.get(item);
if (orderQuantity == null) orderQuantity = 0;
orderQuantity += quantity;
items.put(item, orderQuantity);
}
public void removeItem(String item, String quantity) {
System.out.println("將商品移出購物車");
}
public Map<String, Integer> getItems() {
// 程式碼省略
return null;
}
@Remove
public void clearItems() {
items.clear();
}
}
關鍵註解:
@Stateful:標記為有狀態會話 Bean。@Remove:呼叫此方法後,容器會銷毀該 Bean 實例。有狀態會話 Bean 在實務開發中較少使用,本文僅作引導。深入學習請參考官方文件與專書。
更多內容請見:beniao.blogjava.net