0

I have a messageListener which purpose is to start clients implementing the Client-interface. The different implementations of the Client-interface is not know at compile time.

The messageListener uses the Launcher-bean to start the clients. So my problem is I need to construct a Launcher-bean that has the selected implementation of the Client-interface injected into it. Im not sure how to do this, or should i approch the problem differently?

public class MyMessageConsumer implements MessageListener {
    public void onMessage(Message message) {
        String clientType = message.getClientType();

        //Here i need to construct a launcher-bean, which has the correct Client-implementation injected

        launcher.startClient(message);
    }   
}

public class Launcher {

    @Inject
    private Client client;

    public void startClient(Message message) {
        ...

        client.start(message);
    }

}

edit: I realised that the tricky part is not finding the correct implementation, but that i need the Consumption of a message to happen as a new request. Is it possible to understand what im after?

Aksel Willgert
  • 10,807
  • 5
  • 48
  • 70
  • if you have small set of `Client` implementations, you can inject all of them into your listener, select correct implementation and pass it to `Launcher` constructor. Or you can even pass it as a second parameter to `startClient` method – hoaz Dec 05 '12 at 15:46
  • now that you say it, it is obvious. never thought about making the listener managed. should be simple. – Aksel Willgert Dec 05 '12 at 16:20
  • But when i think more about it, the real problem is that i have only one instance of MessageListener (So i guess that would make it @ApplicationScoped). But i need new client-instances for every time I launch a client. So I guess those would be some lesser scope (request or session) – Aksel Willgert Dec 05 '12 at 17:15
  • if you want to reuse client instance between requests and have a unique instance whenever you launch a client, then it should be session scope – hoaz Dec 05 '12 at 17:33

1 Answers1

0

What you want is a producer.

This way you separate the client of the contextual instance and the producer. So inject them into a producer and have it decide what to use.

For this to be transparent and to avoid ambiguous dependency you could produce a value with @Dynamic qualifier.

@Inject
@Dynamic
Foo foo;

..............................

@Produces
@Dynamic
public Foo getFoo() {
//find out what implementation to use and return it  

Creating your own qualifier and producer is very simple to google.

Karl Kildén
  • 2,305
  • 20
  • 32