How to use play.api.inject.Injector to get an annotated instance?

518 views
Skip to first unread message

Guofeng Zhang

unread,
May 20, 2016, 2:08:03 AM5/20/16
to play-fr...@googlegroups.com
Hi,

I could get the Injector using
  Injector injector = play.api.Play.current().injector() ;
For  
  bind(Hello.class).to(EnglishHello.class);
I could use 
   Hello hello = injector.instanceOf(Hello.class)
to get the instance.

But if the binding is rewritten as
    bind(Hello.class).annotatedWith(Names.named("en")).to(EnglishHello.class);
I do not know how to get the instance using the above way.

Your help is appreciated

Thanks

Guofeng

Greg Methvin

unread,
May 20, 2016, 2:14:06 AM5/20/16
to play-framework
Hi Guofeng,

You'd use the Injector#instanceOf(BindingKey) method, and construct a BindingKey with your annotation.

That said, I'm curious why you are trying to retrieve instances directly from the injector. Typically you'd annotate the constructor of your component and have the instance injected automatically by the framework.

Greg

--
You received this message because you are subscribed to the Google Groups "play-framework" group.
To unsubscribe from this group and stop receiving emails from it, send an email to play-framewor...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/play-framework/CAMpUGn3QrA8aRfp60ETKyux89QE76cYkJZ14qNMvq_2Ujgwkhg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.



--
Greg Methvin
Senior Software Engineer

Guofeng Zhang

unread,
May 20, 2016, 3:05:37 AM5/20/16
to play-fr...@googlegroups.com
I use Java, so I use BindingKey.apply() to create an instance of BindingKey, then it solved my issue. Thanks.

For the "curious, I just want to do a post for it.

I met a case I do not know how to use DI to solve it.

I have a class OrderSynSubscriber, that is the subclass of AbstractSubscriber. I create a source for it
 Source<Order, ActorRef> orderSource =
     Source.actorPublisher(OrderSynSubscriber.props(.....));

I do not know how to use DI for OrderSynSubscriber. So I get the instance from Injector manually in the class.

The props() is defined as:
public static Props props(String orderUrl, String clientId, Date synTime)
{
        return Props.create(OrderSynSubscriber.class, ()->new OrderSynSubscriber(orderUrl, clientId, synTime));
}

Your advice is appreciated.

Thanks for your help!.

Guofeng



Greg Methvin

unread,
May 20, 2016, 5:19:37 AM5/20/16
to play-framework
I'm assuming you're creating an actor. If you're using Guice, our documentation on dependency injecting actors might help.


For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages