EJB攔截


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

攔截器方法可以應用在三個層面上的約束

  • Default - 預設的攔截器被呼叫內deployment.Default攔截每個bean只能應用於通過XML(ejb-jar.xml)。

  • Class - 類級別攔截所有的bean的方法被呼叫。類級別攔截器可以應用通過XML註釋(ejb-jar.xml)。

  • Method - 方法級別的攔截器是一個特定的bean的方法呼叫。方法級的攔截器可以應用通過XML註釋(ejb-jar.xml)。

我們在這裡討論類級別攔截。

Interceptor class

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

Remote Interface

import javax.ejb.Remote;

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

Intercepted Stateless EJB

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

範例應用程式

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

Step 描述
1 Create a project with a name EjbComponent under a package com.tutorialspoint.interceptoras explained in the EJB - Create Application chapter. You can also use the project created inEJB - Create Application chapter as such for this chapter to understand intercepted ejb concepts.
2 Create LibraryBean.java and LibraryBeanRemote under packagecom.tutorialspoint.interceptor as explained in the EJB - Create Application chapter. Keep rest of the files unchanged.
3 Clean and Build the application to make sure business logic is working as per the requirements.
4 Finally, deploy the application in the form of jar file on JBoss Application Server. JBoss Application server will get started automatically if it is not started yet.
5 Now create the ejb client, a console based application in the same way as explained in theEJB - Create Application chapter under topic Create Client to access EJB.

EJBComponent (EJB Module)

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 Client)

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
  • 這些屬性是用來初始化InitialContext物件的Java命名服務

  • 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 
1. Add Book
2. Exit 
Enter 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物件。

  • JNDI查詢testInterceptedEjb()方法,完成了名稱 - “LibraryBean/remote”獲得遠端業務物件(無狀態EJB)。

  • 如果使用者輸入1,系統要求輸入書籍名稱和節約使用無狀態的對談bean addBook()方法的書。對談Bean儲存在它的範例變數的書。

  • 如果使用者輸入2,系統檢索書使用狀態對談Bean getBooks()方法和退出。

Run Client to access EJB

在專案資源管理器中找到EJBTester.java。右鍵點選上EJBTester類,並選擇run file.

在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