📜  EJB-拦截器

📅  最后修改于: 2020-11-16 06:21:27             🧑  作者: Mango


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。

Step Description
1

Create a project with a name EjbComponent under a package com.tutorialspoint.interceptor as explained in the EJB – Create Application chapter. You can also use the project created in EJB – Create Application chapter as such for this chapter to understand intercepted EJB concepts.

2

Create LibraryBean.java and LibraryBeanRemote under package com.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 the EJB – Create Application chapter under topic Create Client to access 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 bookShelf;    

   public LibraryBean() {
      bookShelf = new ArrayList();
   }

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

   public List getBooks() {
      return bookShelf;
   }   
}
  • 在JBOSS上部署EjbComponent项目后,请注意jboss日志。

  • JBoss已经为我们的会话bean − LibraryBean / remote自动创建了一个JNDI条目。

  • 我们将使用该查找字符串来获取类型为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 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 Application Server日志输出中验证以下输出。

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