10.12.2012 Views

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

The Java EE 5 Tutorial (PDF) - Oracle Software Downloads

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

A <strong>Java</strong> <strong>EE</strong> ApplicationThat Uses the JMS API with a Session Bean<br />

958<br />

operations and so is simpler than the client program in Chapter 23, “A Message-Driven Bean<br />

Example.” <strong>The</strong> program uses dependency injection to obtain the Publisher enterprise bean’s<br />

business interface:<br />

@EJB(name="PublisherRemote")<br />

static private PublisherRemote publisher;<br />

<strong>The</strong> program then calls the bean’s business method twice.<br />

Coding the Publisher Session Bean<br />

<strong>The</strong> Publisher bean is a stateless session bean that has one business method. <strong>The</strong> Publisher bean<br />

uses a remote interface rather than a local interface because it is accessed from the application<br />

client.<br />

<strong>The</strong> remote interface, clientsessionmdb-ejb/src/java/sb/PublisherRemote.java,<br />

declares a single business method, publishNews.<br />

<strong>The</strong> bean class, clientsessionmdb-ejb/src/java/sb/PublisherBean.java, implements the<br />

publishNews method and its helper method chooseType. <strong>The</strong> bean class also injects<br />

SessionContext, ConnectionFactory, and Topic resources and implements @PostConstruct<br />

and @PreDestroy callback methods. <strong>The</strong> bean class begins as follows:<br />

@Stateless<br />

@Remote({PublisherRemote.class})<br />

public class PublisherBean implements PublisherRemote {<br />

@Resource<br />

private SessionContext sc;<br />

@Resource(mappedName="jms/ConnectionFactory")<br />

private ConnectionFactory connectionFactory;<br />

@Resource(mappedName="jms/Topic")<br />

private Topic topic;<br />

...<br />

<strong>The</strong> @PostConstruct callback method of the bean class, makeConnection, creates the<br />

Connection used by the bean. <strong>The</strong> business method publishNews creates a Session and a<br />

MessageProducer and publishes the messages.<br />

<strong>The</strong> @PreDestroy callback method, endConnection, deallocates the resources that were<br />

allocated by the @PostConstruct callback method. In this case, the method closes the<br />

Connection.<br />

<strong>The</strong> <strong>Java</strong> <strong>EE</strong> 5<strong>Tutorial</strong> • June 2010

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

Saved successfully!

Ooh no, something went wrong!