12.07.2015 Views

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

Beginning Java EE 6 with GlassFish 3, Second Edition

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 6 ■ ENTERPRISE JAVA BEANS}}book.setIsbn("1-84023-742-2");book.setNbOfPage(354);bookEJB.createBook(book);One of the differences between a pure <strong>Java</strong> class and a session bean is shown in Listing 6-2; even ifthe code is similar, the Main class doesn’t create an instance of the BookEJB using the new keyword;instead, the class needs to first obtain a reference to the EJB, either by injection or by JNDI lookup,before calling a method. This mechanism is used because the EJB runs in a managed environment. Itneeds to be deployed in a container (embedded or not).Like most <strong>Java</strong> <strong>EE</strong> 6 components, EJBs need metadata to inform the container of required actions(transaction demarcation) or services to inject. Metadata can take the form of either annotations orXML. EJBs can be deployed <strong>with</strong> the optional ejb-jar.xml deployment descriptor, which will overrideannotations. With configuration by exception, a single annotation (@Stateless in this case) is enough toturn a POJO into an EJB because the container applies all the default behavior.EJB ContainerAs mentioned, an EJB is a server-side component and needs to be executed in a container. This runtimeenvironment provides core features common to many enterprise applications such as the following:• Remote client communication: Without writing any complex code, an EJB client(another EJB, a user interface, a batch process, etc.) can invoke methods remotelyvia standard protocols.• Dependency injection: The container can inject several resources into an EJB (JMSdestinations and factories, datasources, other EJBs, environment variables, and soon).• State management: For stateful session beans, the container manages their statetransparently. You can maintain state for a particular client, as if you weredeveloping a desktop application.• Pooling: For stateless beans and MDBs, the container creates a pool of instancesthat can be shared by multiple clients. Once invoked, an EJB returns to the pool tobe reused instead of being destroyed.• Component life cycle: The container is responsible for managing the life cycle ofeach component.• Messaging: The container allows MDBs to listen to destinations and consumemessages <strong>with</strong>out too much JMS plumbing.183

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!