EJB依賴注入
EJB 3.0規範提供了注釋字段或setter方法注入依賴可以應用。 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.tutorialspoint.stateless.LibraryPersistentBean") public void setLibraryPersistentBean( LibraryPersistentBeanRemote libraryBean) { this.libraryBean = libraryBean; } ... }
@Resource 使用步驟
@Resource 通常用於注入EJB容器提供單例。
public class LibraryMessageBean implements MessageListener { @Resource private MessageDrivenContext mdctx; ... }
示例應用程序
讓我們創建一個測試EJB應用程序來測試EJB服務的依賴注入。
Step | Description |
---|---|
1 | Create a project with a name EjbComponent under a package com.tutorialspoint.timer as explained in the EJB - Create Application chapter. |
3 | Use Beans created in the EJB - Message Driven Bean chapter. Keep rest of the files unchanged. |
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 theEJB - Create Application chapter under topic Create Client to access EJB. |
EJBComponent (EJB Module)
LibraryMessageBean.java
package com.tuturialspoint.messagebean; import com.tutorialspoint.entity.Book; import com.tutorialspoint.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 Client)
EJBTester.java
package com.tutorialspoint.test; import com.tutorialspoint.entity.Book; import com.tutorialspoint.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 1. Add Book 2. Exit Enter 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對象。
-
JNDI查找testStatefulEjb()方法,完成了名字 - “/queue/BookQueue”在JBoss獲得參考。發件人使用隊列會話創建。
-
然後用戶顯示一個庫存儲的用戶界麵和他/她被要求輸入選擇。
-
如果用戶輸入1,係統要求輸入書籍名稱和發件人發送本書的名字來排隊。當JBoss容器接收到這個消息隊列,它會調用我們的消息驅動bean的onMessage方法。消息驅動bean保存使用狀態會話bean addBook()方法的書。會話Bean持久化這本書中通過EntityManager調用數據庫。
-
如果用戶輸入2,然後是另一個JNDI查找名字 - “LibraryStatefulSessionBean/remote”獲取遠程業務對象(狀態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被使用LibraryPersistentBean使用@ EJB注釋注入的情況下例外MessageDrivenContext對象用於回滾事務。