简体   繁体   中英

How to annotate injector.getInstance?

I want to inject an instance from Guice injector in my unitTest.

Which diffrentiator can I use?

I know @annotation mechanism is used in ctor params

but junit doesn't allow ctor with params.

should I use class fields' @annotation ?

 public void setUp() throws Exception {
    RoutingResponseRepository routingResponseRepository = injector.getInstance(RoutingResponseRepository.class);
}

eg

I want

@firstType RoutingResponseRepository

and

@secondType RoutingResponseRepository

For testing, you could just inject into your test-case-instance. Then you can use your injection-points just as you would in production code:

@Inject
@SecondType 
private RoutingResponseRepository;

@Before
public void setUp() {
    Guice.createInjector().injectMembers(this);
}

without caring about Types and Keys.

Use Injector.getInstance(Key) :

injector.getInstance(Key.get(RoutingResponseRepository.class, firstType.class))

When referring to a binding, Guice internally uses an immutable Key instance, which refers to an annotation status (a binding annotation class, a binding annotation instance, or no binding annotation) combined with a type (a class literal, a Type instance, or a TypeLiteral). Matching this matrix, there are 9 different overloads of Key.get , which is the static factory method to get these Key objects. Overloads that take Class<?> are offered just for the sake of convenience.

In general, any time you want to represent a parameterized or annotated type (like in getInstance or bind ), you can use an overload that takes a Key instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM