Ejb-callbacks

提供:Dev Guides
移動先:案内検索

EJB-コールバック

コールバックは、エンタープライズBeanのライフサイクルを傍受できるメカニズムです。 EJB 3.0仕様では、コールバックハンドラメソッドが作成されるコールバックが指定されています。 EJBコンテナはこれらのコールバックを呼び出します。 EJBクラス自体または別のクラスでコールバックメソッドを定義できます。 EJB 3.0は、コールバック用の多くの注釈を提供しています。

以下は、ステートレスBeanのコールバックアノテーションのリストです-

Annotation Description
@PostConstruct Invoked when a bean is created for the first time.
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.

以下は、ステートフルBeanのコールバックアノテーションのリストです-

Annotation Description
@PostConstruct Invoked when a bean is created for the first time.
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.
@PostActivate Invoked when a bean is loaded to be used.
@PrePassivate Invoked when a bean is put back to bean pool.

以下は、メッセージ駆動型Beanのコールバックアノテーションのリストです-

Annotation Description
@PostConstruct Invoked when a bean is created for the first time.
@PreDestroy Invoked when a bean is removed from the bean pool or is destroyed.

以下は、エンティティBeanのコールバックアノテーションのリストです-

Annotation Description
@PrePersist Invoked when an entity is created in database.
@PostPersist Invoked after an entity is created in database.
@PreRemove Invoked when an entity is deleted from the database.
@PostRemove Invoked after an entity is deleted from the database.
@PreUpdate Invoked before an entity is to be updated in the database.
@PostLoad Invoked when a record is fetched from database and loaded into the entity.

応用例

テストEJBアプリケーションを作成して、EJBのさまざまなコールバックをテストしましょう。

Step Description
1 Create a project with a name EjbComponent under a package com.finddevguides.stateless as explained in the EJB - Create Application chapter. You can also use the project created in EJB - Persistence chapter as such for this chapter to add various callbacks to EJB.
2 Create LibrarySessionBean.java and LibrarySessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged.
3 Use Beans created in the EJB - Persistence chapter. Add callback methods as shown below. Keep rest of the files unchanged.
4 Create a java class BookCallbackListener under package com.finddevguides.callback. This class will demonstrates the separation of callback methods.
5 Clean and Build the application to make sure business logic is working as per the requirements.
6 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.
7 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モジュール)

BookCallbackListener.java

package com.finddevguides.callback;

import javax.persistence.PrePersist;
import javax.persistence.PostLoad;
import javax.persistence.PostPersist;
import javax.persistence.PostRemove;
import javax.persistence.PostUpdate;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;

import com.finddevguides.entity.Book;

public class BookCallbackListener {

   @PrePersist
   public void prePersist(Book book) {
      System.out.println("BookCallbackListener.prePersist:"
         + "Book to be created with book id: "+book.getId());
   }

   @PostPersist
   public void postPersist(Object book) {
      System.out.println("BookCallbackListener.postPersist::"
         + "Book created with book id: "+((Book)book).getId());
   }

   @PreRemove
   public void preRemove(Book book) {
      System.out.println("BookCallbackListener.preRemove:"
         + " About to delete Book: " + book.getId());
   }

   @PostRemove
   public void postRemove(Book book) {
      System.out.println("BookCallbackListener.postRemove::"
         + " Deleted Book: " + book.getId());
   }

   @PreUpdate
   public void preUpdate(Book book) {
      System.out.println("BookCallbackListener.preUpdate::"
         + " About to update Book: " + book.getId());
   }

   @PostUpdate
   public void postUpdate(Book book) {
      System.out.println("BookCallbackListener.postUpdate::"
         + " Updated Book: " + book.getId());
   }

   @PostLoad
   public void postLoad(Book book) {
      System.out.println("BookCallbackListener.postLoad::"
         + " Loaded Book: " + book.getId());
   }
}

Book.java

package com.finddevguides.entity;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="books")
public class Book implements Serializable{

   private int id;
   private String name;

   public Book() {
   }

   @Id
   @GeneratedValue(strategy= GenerationType.IDENTITY)
   @Column(name="id")
   public int getId() {
      return id;
   }

   public void setId(int id) {
      this.id = id;
   }

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }
}

LibraryStatefulSessionBean.java

package com.finddevguides.stateful;

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

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Stateful;

@Stateful
public class LibraryStatefulSessionBean
   implements LibraryStatefulSessionBeanRemote {
   List<String> bookShelf;

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

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

   public List<String> getBooks() {
      return bookShelf;
   }

   @PostConstruct
   public void postConstruct() {
      System.out.println("LibraryStatefulSessionBean.postConstruct::"
         + " bean created.");
   }

   @PreDestroy
   public void preDestroy() {
      System.out.println("LibraryStatefulSessionBean.preDestroy:"
         + " bean removed.");
   }

   @PostActivate
   public void postActivate() {
      System.out.println("LibraryStatefulSessionBean.postActivate:"
         + " bean activated.");
   }

   @PrePassivate
   public void prePassivate() {
      System.out.println("LibraryStatefulSessionBean.prePassivate:"
         + " bean passivated.");
   }
}

LibraryStatefulSessionBeanRemote.java

package com.finddevguides.stateful;

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

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

LibraryPersistentBean.java

package com.finddevguides.stateless;

import com.finddevguides.entity.Book;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
public class LibraryPersistentBean
   implements LibraryPersistentBeanRemote {

   public LibraryPersistentBean() {}

   @PersistenceContext(unitName="EntityEjbPU")
   private EntityManager entityManager;

   public void addBook(Book book) {
      entityManager.persist(book);
   }

   public List<Book> getBooks() {
      return entityManager.createQuery("From Book")
         .getResultList();
   }

   @PostConstruct
   public void postConstruct() {
      System.out.println("postConstruct:: LibraryPersistentBean session bean"
         + " created with entity Manager object: ");
   }

   @PreDestroy
   public void preDestroy() {
      System.out.println("preDestroy: LibraryPersistentBean session"
      + " bean is removed ");
   }
}

LibraryPersistentBeanRemote.java

package com.finddevguides.stateless;

import com.finddevguides.entity.Book;
import java.util.List;
import javax.ejb.Remote;

@Remote
public interface LibraryPersistentBeanRemote {

   void addBook(Book bookName);

   List<Book> getBooks();

}
  • EjbComponentプロジェクトをJBOSSにデプロイするとすぐに、jbossログに注目してください。
  • JBossは、セッションBeanのJNDIエントリ- LibraryPersistentBean/remote を自動的に作成しました。
  • この検索文字列を使用して、タイプのリモートビジネスオブジェクトを取得します- com.finddevguides.stateless.LibraryPersistentBeanRemote

JBoss Application Serverのログ出力

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

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.finddevguides.test;

import com.finddevguides.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.testEntityEjb();
   }

   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 testEntityEjb() {
      try {
      int choice = 1;

      LibraryPersistentBeanRemote libraryBean =
      (LibraryPersistentBeanRemote)
      ctx.lookup("LibraryPersistentBean/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オブジェクトを初期化します。
  • testStatelessEjb()メソッドでは、jndiルックアップが「LibrarySessionBean/remote」という名前で実行され、リモートビジネスオブジェクト(ステートレスEJB)が取得されます。
  • 次に、ユーザーにライブラリストアのユーザーインターフェイスが表示され、ユーザーは選択肢を入力するよう求められます。
  • ユーザーが1を入力すると、システムはブック名を要求し、ステートレスセッションBeanのaddBook()メソッドを使用してブックを保存します。 セッションBeanはデータベースに本を保存しています。
  • ユーザーが2を入力すると、システムはステートレスセッションBeanのgetBooks()メソッドを使用して本を取得し、終了します。

クライアントを実行して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 Application Serverのログ出力

JBossログで次のコールバックエントリを見つけることができます

14:08:34,293 INFO  [STDOUT] postConstruct:: LibraryPersistentBean session bean created with entity Manager object
...
16:39:09,484 INFO  [STDOUT] BookCallbackListener.prePersist:: Book to be created with book id: 0
16:39:09,531 INFO  [STDOUT] BookCallbackListener.postPersist:: Book created with book id: 1
16:39:09,900 INFO  [STDOUT] BookCallbackListener.postLoad:: Loaded Book: 1
...