3

What i'm trying to do is next: I have dispatcher that will receive messages of different types and route them to handlers. Dispatcher holds map of , every MessageHandler can process his type of messages, and every handler should register in dispatcher.

So i have "Dispatcher" service which implement interface:

public interface Dispatcher{
   public void register(IMessageHandler handler);
   public void handle(IMessage message);
}

and several beans that implement interface IMessageHandler:

public interface IMessageHandler{
   public void handle(IMessage message);
}

IMessage is also an interface.

I need this instances of IMessageHandler to call "register" method on Dispatcher to register themself, so dispatcher can distribute messages to appropriate handlers.

For now i do next:

@Service(IMessageHandler.class)
public class MessageBHandler implements IMessageHandler {

    @Inject
    @Reference
    Dispatcher dispatcher;

  @PostConstruct
  public void registerMyself(){
     dispatcher.register(this);
  }
...

}

But i see in logs that Dispatcher gets create twice. How can i make him singleton?

partTimeNinja
  • 191
  • 1
  • 12

1 Answers1

0

If you don't specify the scope of your Dispacher implementation, it defaults to the @Dependent scope. That means that there will be a different Dispacher instance for each MessageHandler.

Try setting the scope of your Dispacher implementation to @ApplicationScoped.

See: Using Scopes.

FeinesFabi
  • 1,147
  • 2
  • 12
  • 25