In ejb3, an MDB (Message-driven bean) is a pojo that implements the messagelistener interface. Below is a simple MDB.
@ Messagedriven (activationconfig = {
@ Activationconfigproperty (propertyname = "destinationtype ",
Propertyvalue = "javax. JMS. queue "),
@ Activationconfigproperty (propertyname = "destination ",
Propertyvalue = "queue/testqueue ")})
Public class SimpleMDB implements MessageListener {
Public void onMessage (Message message ){
Try {
System. out. println ("Receive Message:" +
(TextMessage) message). getText ());
} Catch (JMSException e ){
E. printStackTrace ();
}
}
}
It must be marked as @ MessageDriven. The Destination monitored by it is injected by annotation attributes.
The following is a StatelessBean that sends messages:
@ Remote
Public interface IMessageSender {
Public void sendMessage (String content) throws Exception;
}
@ Stateless
@ Remote
Public class MessageSender implements IMessageSender {
@ Resource (mappedName = "ConnectionFactory ")
Private ConnectionFactory factory;
@ Resource (mappedName = "queue/testQueue ")
Private Queue queue;
Public void sendMessage (String content) throws Exception {
Connection cn = factory. createConnection ();
Session session = cn. createSession (false,
Session. AUTO_ACKNOWLEDGE );
MessageProducer producer = session. createProducer (queue );
Producer. send (session. createTextMessage (content ));
}
}
This EJB has only one SendMessage method. ConnectionFactory and Queue are injected by annotation.
Next is the client:
Public class MessageSenderClient {
Public static void main (String [] args) throws Exception {
Properties props = new Properties ();
Props. setProperty (Context. INITIAL_CONTEXT_FACTORY,
"Org. jnp. interfaces. NamingContextFactory ");
Props. setProperty (Context. PROVIDER_URL, "localhost: 2099 ");
Context context = new initialcontext (props );
Imessagesender messagesender = (imessagesender)
Context. Lookup ("messagesender/remote ");
Messagesender. sendmessage ("hello ");
}
}
It finds the above EJB through JNDI and then calls sengmessage.