Ejb-dependency-injection

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

EJB-依存性注入

EJB 3.0仕様は、フィールドまたはセッターメソッドに適用して依存関係を注入できる注釈を提供します。 EJBコンテナは、グローバルJNDIレジストリを使用して依存関係を見つけます。 EJB 3.0では、依存性注入のために次の注釈が使用されます。

  • @ EJB -他のEJB参照を注入するために使用されます。
  • @ Resource -sessionContext、timerServiceなどのデータソースまたはシングルトンサービスの注入に使用

@EJBを使用する手順

@EJBは、次の方法でフィールドまたはメソッドで使用することができます-

public class LibraryMessageBean implements MessageListener {
  //dependency injection on field.
   @EJB
   LibraryPersistentBeanRemote libraryBean;
   ...
}
public class LibraryMessageBean implements MessageListener {

   LibraryPersistentBeanRemote libraryBean;

  //dependency injection on method.
   @EJB(beanName="com.finddevguides.stateless.LibraryPersistentBean")
   public void setLibraryPersistentBean(
   LibraryPersistentBeanRemote libraryBean)
   {
      this.libraryBean = libraryBean;
   }
   ...
}

@Resourceを使用する手順

@Resourceは通常、EJBコンテナが提供するシングルトンを注入するために使用されます。

public class LibraryMessageBean implements MessageListener {
   @Resource
   private MessageDrivenContext mdctx;
   ...
}

応用例

EJBでDependency InjectionサービスをテストするテストEJBアプリケーションを作成しましょう。

Step Description
1 Create a project with a name EjbComponent under a package com.finddevguides.timer as explained in the EJB - Create Application chapter.
2 Use Beans created in the EJB - Message Driven Bean 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モジュール)

LibraryMessageBean.java

package com.tuturialspoint.messagebean;

import com.finddevguides.entity.Book;
import com.finddevguides.stateless.LibraryPersistentBeanRemote;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

@MessageDriven(
   name = "BookMessageHandler",
   activationConfig = {
      @ActivationConfigProperty( propertyName = "destinationType",
                                 propertyValue = "javax.jms.Queue"),
      @ActivationConfigProperty( propertyName = "destination",
                                 propertyValue ="/queue/BookQueue")
   }
)
public class LibraryMessageBean implements MessageListener {

   @Resource
   private MessageDrivenContext mdctx;

   @EJB
   LibraryPersistentBeanRemote libraryBean;

   public LibraryMessageBean() {
   }

   public void onMessage(Message message) {
      ObjectMessage objectMessage = null;
      try {
         objectMessage = (ObjectMessage) message;
         Book book = (Book) objectMessage.getObject();
         libraryBean.addBook(book);

      }catch (JMSException ex) {
         mdctx.setRollbackOnly();
      }
   }
}

EJBTester(EJBクライアント)

EJBTester.java

package com.finddevguides.test;

import com.finddevguides.entity.Book;
import com.finddevguides.stateless.LibraryPersistentBeanRemote;
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.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
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.testMessageBeanEjb();
   }

   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 testMessageBeanEjb() {

      try {
         int choice = 1;
         Queue queue = (Queue) ctx.lookup("/queue/BookQueue");
         QueueConnectionFactory factory =
         (QueueConnectionFactory) ctx.lookup("ConnectionFactory");
         QueueConnection connection =  factory.createQueueConnection();
         QueueSession session = connection.createQueueSession(
         false, QueueSession.AUTO_ACKNOWLEDGE);
         QueueSender sender = session.createSender(queue);

         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);
               ObjectMessage objectMessage =
               session.createObjectMessage(book);
               sender.send(objectMessage);
            } else if (choice == 2) {
               break;
            }
         }

         LibraryPersistentBeanRemote libraryBean =
         (LibraryPersistentBeanRemote)
         ctx.lookup("LibraryPersistentBean/remote");

         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オブジェクトを初期化します。
  • testStatefulEjb()メソッドでは、jndiルックアップは名前-"/queue/BookQueue"で実行され、Jbossで利用可能なキューの参照を取得します。 次に、キューセッションを使用して送信者が作成されます。
  • 次に、ユーザーにライブラリストアのユーザーインターフェイスが表示され、選択肢を入力するように求められます。
  • ユーザーが1を入力すると、システムは書籍名を要求し、送信者は書籍名をキューに送信します。 JBossコンテナがキューでこのメッセージを受信すると、メッセージ駆動型BeanのonMessageメソッドを呼び出します。 メッセージ駆動型Beanは、ステートフルセッションBeanのaddBook()メソッドを使用して本を保存します。 セッションBeanは、EntityManager呼び出しを介してデータベースに本を保持しています。
  • ユーザーが2を入力すると、「LibraryStatefulSessionBean/remote」という名前で別のjndiルックアップが行われ、リモートビジネスオブジェクト(ステートフルEJB)が再度取得され、書籍のリストが作成されます。

クライアントを実行して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 EJB
**********************
Welcome to Book Store
**********************
Options
1. Add Book
2. Exit
Enter Choice: 2
Book(s) entered so far: 2
1. learn java
1. learn EJB
BUILD SUCCESSFUL (total time: 15 seconds)

上記の出力は、メッセージ駆動型Beanがメッセージを受信して​​永続ストレージに本を保存し、本がデータベースから取得されることを示しています。

メッセージ駆動型Beanは、@ EJBアノテーションを使用して注入されたLibraryPersistentBeanを使用しており、例外の場合、MessageDrivenContextのオブジェクトがトランザクションのロールバックに使用されます。