EJB - 無狀態 Bean



無狀態會話 Bean 是一種企業 Bean 型別,通常用於執行獨立操作。顧名思義,無狀態會話 Bean 沒有與任何關聯的客戶端狀態,但它可以保留其例項狀態。EJB 容器通常會建立一些無狀態 Bean 物件的池,並使用這些物件來處理客戶端的請求。由於池的存在,例項變數的值在查詢/方法呼叫之間不保證相同。

建立無狀態 EJB 的步驟

以下是建立無狀態 EJB 所需的步驟:

  • 建立一個公開業務方法的遠端/本地介面。

  • 此介面將由 EJB 客戶端應用程式使用。

  • 如果 EJB 客戶端與要部署 EJB 會話 Bean 的環境相同,則使用 @Local 註解。

  • 如果 EJB 客戶端與要部署 EJB 會話 Bean 的環境不同,則使用 @Remote 註解。

  • 建立一個實現上述介面的無狀態會話 Bean。

  • 使用 @Stateless 註解表示它是無狀態 Bean。EJB 容器會在部署期間自動建立讀取此註解時所需的相應配置或介面。

遠端介面

import javax.ejb.Remote;
 
@Remote
public interface LibrarySessionBeanRemote {
   //add business method declarations
}

無狀態 EJB

@Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
   //implement business method 
}

示例應用程式

讓我們建立一個測試 EJB 應用程式來測試無狀態 EJB。

步驟 描述
1

在包 com.tutorialspoint.stateless 下建立一個名為 EjbComponent 的專案,如EJB - 建立應用程式章節中所述。您也可以將EJB - 建立應用程式章節中建立的專案用於本章,以瞭解無狀態 EJB 概念。

2

建立 LibrarySessionBean.javaLibrarySessionBeanRemote,如EJB - 建立應用程式章節中所述。保持其餘檔案不變。

3

清理並構建應用程式,以確保業務邏輯按要求工作。

4

最後,將應用程式以 jar 檔案的形式部署到 JBoss 應用伺服器上。如果 JBoss 應用伺服器尚未啟動,它將自動啟動。

5

現在建立 EJB 客戶端,一個基於控制檯的應用程式,方法與EJB - 建立應用程式章節中主題建立訪問 EJB 的客戶端中所述相同。

EjbComponent(EJB 模組)

LibrarySessionBeanRemote.java

package com.tutorialspoint.stateless;
 
import java.util.List;
import javax.ejb.Remote;
 
@Remote
public interface LibrarySessionBeanRemote {
   void addBook(String bookName);
   List getBooks();
}

LibrarySessionBean.java

 
package com.tutorialspoint.stateless;
 
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
 
@Stateless
public class LibrarySessionBean implements LibrarySessionBeanRemote {
    
   List<String> bookShelf;    
 
   public LibrarySessionBean() {
      bookShelf = new ArrayList<String>();
   }
 
   public void addBook(String bookName) {
      bookShelf.add(bookName);
   }    
 
   public List<String> getBooks() {
      return bookShelf;
   }
}
  • 在您將 EjbComponent 專案部署到 JBOSS 上後,請注意 jboss 日誌。

  • JBoss 已自動為我們的會話 Bean 建立了一個 JNDI 條目 - LibrarySessionBean/remote

  • 我們將使用此查詢字串來獲取型別為 com.tutorialspoint.stateless.LibrarySessionBeanRemote 的遠端業務物件。

JBoss 應用伺服器日誌輸出

...
16:30:01,401 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
   LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
   LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
16:30:02,723 INFO  [SessionSpecContainer] Starting jboss.j2ee:jar=EjbComponent.jar,name=LibrarySessionBean,service=EJB3
16:30:02,723 INFO  [EJBContainer] STARTED EJB: com.tutorialspoint.stateless.LibrarySessionBeanRemote ejbName: LibrarySessionBean
16:30:02,731 INFO  [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:
 
   LibrarySessionBean/remote - EJB3.x Default Remote Business Interface
   LibrarySessionBean/remote-com.tutorialspoint.stateless.LibrarySessionBeanRemote - EJB3.x Remote Business Interface
...   

EJBTester(EJB 客戶端)

jndi.properties

java.naming.factory.initial=org.jnp.interfaces.NamingContextFactory
java.naming.factory.url.pkgs=org.jboss.naming:org.jnp.interfaces
java.naming.provider.url=localhost
  • 這些屬性用於初始化 java 命名服務的 InitialContext 物件。

  • InitialContext 物件將用於查詢無狀態會話 Bean。

EJBTester.java

package com.tutorialspoint.test;
   
import com.tutorialspoint.stateful.LibrarySessionBeanRemote;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.naming.NamingException;
 
public class EJBTester {
 
   BufferedReader brConsoleReader = null; 
   Properties props;
   InitialContext ctx;
   {
      props = new Properties();
      try {
         props.load(new FileInputStream("jndi.properties"));
      } catch (IOException ex) {
         ex.printStackTrace();
      }
      try {
         ctx = new InitialContext(props);            
      } catch (NamingException ex) {
         ex.printStackTrace();
      }
      brConsoleReader = 
      new BufferedReader(new InputStreamReader(System.in));
   }
   
   public static void main(String[] args) {
 
      EJBTester ejbTester = new EJBTester();
 
      ejbTester.testStatelessEjb();
   }
   
   private void showGUI() {
      System.out.println("**********************");
      System.out.println("Welcome to Book Store");
      System.out.println("**********************");
      System.out.print("Options \n1. Add Book\n2. Exit \nEnter Choice: ");
   }
   
   private void testStatelessEjb() {
 
      try {
         int choice = 1; 
 
         LibrarySessionBeanRemote libraryBean =
         LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
 
         while (choice != 2) {
            String bookName;
            showGUI();
            String strChoice = brConsoleReader.readLine();
            choice = Integer.parseInt(strChoice);
            if (choice == 1) {
               System.out.print("Enter book name: ");
               bookName = brConsoleReader.readLine();
               Book book = new Book();
               book.setName(bookName);
               libraryBean.addBook(book);          
            } else if (choice == 2) {
               break;
            }
         }
 
         List<Book> booksList = libraryBean.getBooks();
 
         System.out.println("Book(s) entered so far: " + booksList.size());
         int i = 0;
         for (Book book:booksList) {
            System.out.println((i+1)+". " + book.getName());
            i++;
         }       
         LibrarySessionBeanRemote libraryBean1 = 
            (LibrarySessionBeanRemote)ctx.lookup("LibrarySessionBean/remote");
         List<String> booksList1 = libraryBean1.getBooks();
         System.out.println(
            "***Using second lookup to get library stateless object***");
         System.out.println(
            "Book(s) entered so far: " + booksList1.size());
         for (int i = 0; i < booksList1.size(); ++i) {
            System.out.println((i+1)+". " + booksList1.get(i));
         }		 
      } catch (Exception e) {
         System.out.println(e.getMessage());
         e.printStackTrace();
      }finally {
         try {
            if(brConsoleReader !=null) {
               brConsoleReader.close();
            }
         } catch (IOException ex) {
            System.out.println(ex.getMessage());
         }
      }
   }
}

EJBTester 執行以下任務:

  • 從 jndi.properties 載入屬性並初始化 InitialContext 物件。

  • 在 testStatelessEjb() 方法中,使用名稱 - "LibrarySessionBean/remote" 進行 jndi 查詢以獲取遠端業務物件(無狀態 ejb)。

  • 然後向用戶顯示一個圖書館商店使用者介面,並要求他/她輸入選擇。

  • 如果使用者輸入 1,系統將詢問書籍名稱,並使用無狀態會話 Bean 的 addBook() 方法儲存書籍。會話 Bean 將書籍儲存在其例項變數中。

  • 如果使用者輸入 2,系統將使用無狀態會話 Bean 的 getBooks() 方法檢索書籍並退出。

  • 然後使用名稱 - "LibrarySessionBean/remote" 再次進行 jndi 查詢以獲取遠端業務物件(無狀態 EJB),並完成書籍列表。

執行客戶端以訪問 EJB

在專案資源管理器中找到 EJBTester.java。右鍵單擊 EJBTester 類並選擇執行檔案

在 Netbeans 控制檯中驗證以下輸出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 1
Enter book name: Learn Java
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 1
1. Learn Java
***Using second lookup to get library stateless object***
Book(s) entered so far: 0
BUILD SUCCESSFUL (total time: 13 seconds)

再次執行客戶端以訪問 EJB

在專案資源管理器中找到 EJBTester.java。右鍵單擊 EJBTester 類並選擇執行檔案

在 Netbeans 控制檯中驗證以下輸出。

run:
**********************
Welcome to Book Store
**********************
Options 
1. Add Book
2. Exit 
Enter Choice: 2
Book(s) entered so far: 0
***Using second lookup to get library stateless object***
Book(s) entered so far: 1
1. Learn Java
BUILD SUCCESSFUL (total time: 12 seconds)
  • 顯示的輸出可能會有所不同,具體取決於 JBoss 保持了多少個無狀態 EJB 物件。

  • 如果維護單個無狀態 EJB 物件,則在每次查詢後您可能會看到相同的書籍列表。

  • EJB 容器可能會為每次查詢返回相同的無狀態 EJB 物件。

  • 無狀態 EJB Bean 會保留例項變數的值,直到伺服器重新啟動。

廣告