EJB - 攔截器



EJB 3.0 提供了使用帶有 @AroundInvoke 註解的方法攔截業務方法呼叫的規範。攔截器方法在 ejbContainer 呼叫其攔截的業務方法之前被呼叫。以下是攔截器方法的示例簽名

@AroundInvoke
public Object methodInterceptor(InvocationContext ctx) throws Exception {
   System.out.println("*** Intercepting call to LibraryBean method: " 
   + ctx.getMethod().getName());
   return ctx.proceed();
}

攔截器方法可以在三個級別應用或繫結。

  • 預設 - 預設攔截器在部署中的每個 Bean 中被呼叫。預設攔截器只能透過 xml (ejb-jar.xml) 應用。

  • - 類級別攔截器在 Bean 的每個方法中被呼叫。類級別攔截器可以透過註解或 xml(ejb-jar.xml) 應用。

  • 方法 - 方法級別攔截器在 Bean 的特定方法中被呼叫。方法級別攔截器可以透過註解或 xml(ejb-jar.xml) 應用。

我們這裡討論的是類級別攔截器。

攔截器類

package com.tutorialspoint.interceptor;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class BusinessInterceptor {
   @AroundInvoke
   public Object methodInterceptor(InvocationContext ctx) throws Exception {
      System.out.println("*** Intercepting call to LibraryBean method: " 
      + ctx.getMethod().getName());
      return ctx.proceed();
   }
}

遠端介面

import javax.ejb.Remote;

@Remote
public interface LibraryBeanRemote {
   //add business method declarations
}

被攔截的無狀態 EJB

@Interceptors ({BusinessInterceptor.class})
@Stateless
public class LibraryBean implements LibraryBeanRemote {
   //implement business method 
}

示例應用程式

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

步驟 描述
1

com.tutorialspoint.interceptor 包下建立一個名為 EjbComponent 的專案,如EJB - 建立應用程式章節所述。您也可以使用EJB - 建立應用程式章節中建立的專案,以便在本章節中理解被攔截的 EJB 概念。

2

com.tutorialspoint.interceptor 包下建立 LibraryBean.javaLibraryBeanRemote,如EJB - 建立應用程式章節所述。保持其他檔案不變。

3

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

4

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

5

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

EJBComponent(EJB 模組)

LibraryBeanRemote.java

package com.tutorialspoint.interceptor;

import java.util.List;
import javax.ejb.Remote;

@Remote
public interface LibraryBeanRemote {
   void addBook(String bookName);
   List getBooks();
}

LibraryBean.java

package com.tutorialspoint.interceptor;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

@Interceptors ({BusinessInterceptor.class})
@Stateless
public class LibraryBean implements LibraryBeanRemote {
    
   List<String> bookShelf;    

   public LibraryBean() {
      bookShelf = new ArrayList<String>();
   }

   public void addBook(String bookName) {
      bookShelf.add(bookName);
   }    

   public List<String> getBooks() {
      return bookShelf;
   }   
}
  • 一旦您在 JBOSS 上部署了 EjbComponent 專案,請注意 jboss 日誌。

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

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

JBoss 應用伺服器日誌輸出

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

   LibraryBean/remote - EJB3.x Default Remote Business Interface
   LibraryBean/remote-com.tutorialspoint.interceptor.LibraryBeanRemote - 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.LibraryBeanRemote;

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.testInterceptedEjb();
   }
   
   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 testInterceptedEjb() {

      try {
         int choice = 1; 

         LibraryBeanRemote libraryBean =
         LibraryBeanRemote)ctx.lookup("LibraryBean/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++;
         }                
      } 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 物件。

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

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

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

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

執行客戶端以訪問 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
BUILD SUCCESSFUL (total time: 13 seconds)

JBoss 應用伺服器日誌輸出

在 JBoss 應用伺服器日誌輸出中驗證以下輸出。

....
09:55:40,741 INFO  [STDOUT] *** Intercepting call to LibraryBean method: addBook
09:55:43,661 INFO  [STDOUT] *** Intercepting call to LibraryBean method: getBooks
廣告