EJB - Intercepteurs

EJB 3.0 fournit des spécifications pour intercepter les appels de méthodes métier à l'aide de méthodes annotées avec l'annotation @AroundInvoke. Une méthode d'interception est appelée par ejbContainer avant que l'appel de méthode métier ne l'intercepte. Voici l'exemple de signature d'une méthode d'intercepteur

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

Les méthodes d'interception peuvent être appliquées ou liées à trois niveaux.

  • Default - L'intercepteur par défaut est appelé pour chaque bean dans le déploiement. L'intercepteur par défaut ne peut être appliqué que via xml (ejb-jar.xml).

  • Class- L'intercepteur de niveau classe est appelé pour chaque méthode du bean. L'intercepteur de niveau de classe peut être appliqué à la fois par annotation ou via xml (ejb-jar.xml).

  • Method- L'intercepteur de niveau méthode est appelé pour une méthode particulière du bean. L'intercepteur de niveau méthode peut être appliqué à la fois par annotation ou via xml (ejb-jar.xml).

Nous discutons ici de l'intercepteur de niveau Classe.

Classe d'intercepteur

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

Interface à distance

import javax.ejb.Remote;

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

EJB sans état intercepté

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

Exemple d'application

Créons une application EJB de test pour tester les EJB sans état interceptés.

Étape La description
1

Créez un projet avec un nom EjbComponent sous un package com.tutorialspoint.interceptor comme expliqué dans le chapitre EJB - Créer une application . Vous pouvez également utiliser le projet créé dans le chapitre EJB - Créer une application en tant que tel pour ce chapitre pour comprendre les concepts EJB interceptés.

2

Créez LibraryBean.java et LibraryBeanRemote sous le package com.tutorialspoint.interceptor comme expliqué dans le chapitre EJB - Créer une application . Gardez le reste des fichiers inchangé.

3

Nettoyez et créez l'application pour vous assurer que la logique métier fonctionne conformément aux exigences.

4

Enfin, déployez l'application sous forme de fichier jar sur JBoss Application Server. Le serveur d'applications JBoss démarrera automatiquement s'il n'est pas encore démarré.

5

Créez maintenant le client ejb, une application basée sur la console de la même manière que celle expliquée dans le chapitre EJB - Créer une application sous la rubriqueCreate Client to access EJB.

EJBComponent (module 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;
   }   
}
  • Dès que vous déployez le projet EjbComponent sur JBOSS, notez le journal jboss.

  • JBoss a créé automatiquement une entrée JNDI pour notre bean session - LibraryBean/remote.

  • Nous utiliserons cette chaîne de recherche pour obtenir un objet métier distant de type - com.tutorialspoint.interceptor.LibraryBeanRemote

Sortie du journal du serveur d'applications 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 (client 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
  • Ces propriétés sont utilisées pour initialiser l'objet InitialContext du service de nommage java.

  • L'objet InitialContext sera utilisé pour rechercher un bean session sans état.

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 effectue les tâches suivantes -

  • Chargez les propriétés de jndi.properties et initialisez l'objet InitialContext.

  • Dans la méthode testInterceptedEjb (), la recherche jndi est effectuée avec le nom - "LibraryBean / remote" pour obtenir l'objet métier distant (EJB sans état).

  • Ensuite, l'utilisateur voit une interface utilisateur de magasin de bibliothèque et il / elle est invité à entrer un choix.

  • Si l'utilisateur entre 1, le système demande le nom du livre et enregistre le livre à l'aide de la méthode addBook () du bean session sans état. Session Bean stocke le livre dans sa variable d'instance.

  • Si l'utilisateur entre 2, le système récupère les livres à l'aide de la méthode getBooks () du bean session sans état et se ferme.

Exécuter le client pour accéder à EJB

Recherchez EJBTester.java dans l'explorateur de projet. Faites un clic droit sur la classe EJBTester et sélectionnezrun file.

Vérifiez la sortie suivante dans la console 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)

Sortie du journal du serveur d'applications JBoss

Vérifiez la sortie suivante dans la sortie du journal du serveur d'applications 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