雷林鵬分享:EJB回調

  回調是一種機制,可以截獲企業Bean的生命週期。 EJB 3.0規範指定的回調,回調處理方法是要創建。 EJB容器調用這些回調。 EJB類本身或在一個單獨的類,我們可以定義回調方法。 EJB3.0提供了許多回調的註解

  以下是無狀態的bean回調的註解。

  Annotation描述

  @PostConstructmethod is invoked when a bean is created for the first time

  @PreDestroymethod is invoked when a bean is removed from the bean pool or is destroyed.

  Following is the list of callback annotations for stateful bean.

  Annotation描述

  @PostConstructmethod is invoked when a bean is created for the first time

  @PreDestroymethod is invoked when a bean is removed from the bean pool or is destroyed.

  @PostActivatemethod is invoked when a bean is loaded to be used.

  @PrePassivatemethod is invoked when a bean is put back to bean pool.

  Following is the list of callback annotations for message driven bean.

  Annotation描述

  @PostConstructmethod is invoked when a bean is created for the first time

  @PreDestroymethod is invoked when a bean is removed from the bean pool or is destroyed.

  Following is the list of callback annotations for entity bean.

  AnnotationDescription

  @PrePersistmethod is invoked when an entity is created in database.

  @PostPersistmethod is invoked after an entity is created in database.

  @PreRemovemethod is invoked when an entity is deleted from the database.

  @PostRemovemethod is invoked after an entity is deleted from the database.

  @PreUpdatemethod is invoked before an entity is to be updated in the database.

  @PostLoadmethod is invoked when a record is fetched from database and loaded into the entity.

  示例應用程序

  讓我們創建一個測試EJB應用程序來測試各種回調EJB。

  Step描述

  1Create a project with a name EjbComponent under a package com.tutorialspoint.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 ejbs.

  2Create LibrarySessionBean.java and LibrarySessionBeanRemote as explained in the EJB - Create Application chapter. Keep rest of the files unchanged.

  3Use Beans created in the EJB - Persistence chapter. Add callback methods as shown below. Keep rest of the files unchanged.

  4Create a java class BookCallbackListener under package com.tutorialspoint.callback. This class will demonstrates the seperation of callback methods.

  5Clean and Build the application to make sure business logic is working as per the requirements.

  6Finally, 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.

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

  BookCallbackListener.java

  package com.tutorialspoint.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.tutorialspoint.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.tutorialspoint.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.tutorialspoint.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 bookShelf;

  public LibraryStatefulSessionBean(){

  bookShelf = new ArrayList();

  }

  public void addBook(String bookName) {

  bookShelf.add(bookName);

  }

  public List 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.");

  }

  }

  LibraryStatefulSessionBeanRempote.java

  package com.tutorialspoint.stateful;

  import java.util.List;

  import javax.ejb.Remote;

  @Remote

  public interface LibraryStatefulSessionBeanRemote {

  void addBook(String bookName);

  List getBooks();

  }

  LibraryPersistentBean.java

  package com.tutorialspoint.stateless;

  import com.tutorialspoint.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 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.tutorialspoint.stateless;

  import com.tutorialspoint.entity.Book;

  import java.util.List;

  import javax.ejb.Remote;

  @Remote

  public interface LibraryPersistentBeanRemote {

  void addBook(Book bookName);

  List getBooks();

  }

  只要你部署在JBoss EjbComponent項目,就會發現jboss的日誌。

  JBoss已經自動爲我們的會話bean創建一個JNDI條目 -LibraryPersistentBean/remote.

  我們將使用這個查詢字符串來獲得遠程類型的業務對象 -com.tutorialspoint.stateless.LibraryPersistentBeanRemote

  JBoss應用服務器的日誌輸出

  ...

  16:30:01,401 INFO [JndiSessionRegistrarBase] Binding the following Entries in Global JNDI:

  LibraryPersistentBean/remote - EJB3.x Default Remote Business Interface

  LibraryPersistentBean/remote-com.tutorialspoint.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.tutorialspoint.stateless.LibrarySessionBeanRemote ejbName: LibraryPersistentBean

  ...

  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.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 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 /遠程”,以獲得遠程業務對象(無狀態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應用服務器的日誌輸出

  你可以找到以下的回調在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

  (編輯:雷林鵬 來源:網絡|侵刪)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章