Paul
Paul

Reputation: 515

Event not working in Message Driven Bean

I'm trying to generate and handle an event when my MDB receives a message. Here is what I'm doing:

public class MDBBooks implements MessageListener {
@Inject 
private Event<Update> messageReceived;

public MDBLibri() {
}

@Override
public void onMessage(Message message) {
    System.out.println("Message received");
    try {
        Update u = message.getBody(Update.class);
        messageReceived.fire(u);
        if(u != null){
            ... stuff        
        }
    } catch (JMSException ex) {
        System.out.println("JMSException: " + ex.getMessage());
    }
}

public void eventHandler(@Observes Update up) {
    System.out.println("There was an update");
}

}

But it just does not work, the string "There was an update" it's not printed in the glassfish console. I can't really tell what's the problem, my textbook does it the same way pretty much. I'm assuming the event fires fine, but the event handler isn't notified.

Upvotes: 0

Views: 544

Answers (1)

Siliarus
Siliarus

Reputation: 6753

You are correct that the observer method does not get notified. In fact, CDI doesn't even know it exists. The reason is that in CDI, message-driven beans are non-contextual objects. To simplify, they are not considered CDI beans, but you can still inject into them and intercept them.

Now, for CDI to recognize an observer method, you have to place it in a managed bean or a session bean. Quoting the spec:

An observer method is a non-abstract method of a managed bean class or session bean class (or of an extension, as defined in Container lifecycle events).

So a solution for you would be to place your observer method in another class, which is either a managed bean or a session bean.

Upvotes: 2

Related Questions