background image

Coding the Publisher Session Bean

<< Coding the Application Client | Coding the Message-Driven Bean >>
<< Coding the Application Client | Coding the Message-Driven Bean >>

Coding the Publisher Session Bean

operations and so is simpler than the client program in
Chapter 23, "A Message-Driven Bean
Example."
The program uses dependency injection to obtain the Publisher enterprise bean's
business interface:
@EJB(name=
"PublisherRemote")
static private PublisherRemote publisher;
The program then calls the bean's business method twice.
Coding the Publisher Session Bean
The Publisher bean is a stateless session bean that has one business method. The Publisher bean
uses a remote interface rather than a local interface because it is accessed from the application
client.
The remote interface, clientsessionmdb-ejb/src/java/sb/PublisherRemote.java,
declares a single business method, publishNews.
The bean class, clientsessionmdb-ejb/src/java/sb/PublisherBean.java, implements the
publishNews
method and its helper method chooseType. The bean class also injects
SessionContext
, ConnectionFactory, and Topic resources and implements @PostConstruct
and @PreDestroy callback methods. The bean class begins as follows:
@Stateless
@Remote({PublisherRemote.class})
public class PublisherBean implements PublisherRemote {
@Resource
private SessionContext sc;
@Resource(mappedName=
"jms/ConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(mappedName=
"jms/Topic")
private Topic topic;
...
The @PostConstruct callback method of the bean class, makeConnection, creates the
Connection
used by the bean. The business method publishNews creates a Session and a
MessageProducer
and publishes the messages.
The @PreDestroy callback method, endConnection, deallocates the resources that were
allocated by the @PostConstruct callback method. In this case, the method closes the
Connection
.
A Java EE Application That Uses the JMS API with a Session Bean
The Java EE 5 Tutorial · September 2007
966